统一返回包装类,作用是统一后端返回的数据类型,你别一会儿是String,一会Integer,一会Map的形式,统一处理
public class Result {
private String code;
private String msg;
private Object data;
// 无数据返回
public static Result success() {
Result res = new Result();
res.setCode("200");
res.setMsg("成功");
return res;
}
// 有数据返回
public static Result success(Object data) {
Result res = new Result();
res.setCode("200");
res.setMsg("成功");
res.setData(data);
return res;
}
public static Result error() {
Result res = new Result();
res.setCode("500");
res.setMsg("错误");
return res;
}
public static Result error(String code, String msg) {
Result res = new Result();
res.setCode(code);
res.setMsg(msg);
return res;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}@ControllerAdvice标识一个全局异常处理的类,当应用程序中的Controller出现异常时,可以有一个集中的地方来处理这些异常,而不是在每个Controller中单独处理
package org.example.exception;
import org.example.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice("org.example.controller")
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class) // 只要是exception及下面的子类都会捕获
@ResponseBody //返回json串
public Result error(Exception e) {
e.printStackTrace(); //在控制台上打印错误信息
return Result.error();
}
@ExceptionHandler(CustomException.class) // 捕捉抛出的自定义异常
@ResponseBody //返回json串
public Result error(CustomException e) {
return Result.error(e.getCode(), e.getMsg());
}
}自定义异常允许开发者定义特定的错误类型,便于在代码中精确捕获和处理。
异常的继承关系

package org.example.exception;
/**
* @description 自定义异常
*/
public class CustomException extends RuntimeException{
private String code;
private String msg;
public CustomException(String code, String msg) {
this.code = code;
this.msg = msg;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}此controller一般用于写用户处理登录注册等和业务不相关的接口
package org.example.controller;
import org.example.common.Result;
import org.example.exception.CustomException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
@RestController
public class WebController {
@GetMapping("/hello")
public Result hello() {
return Result.success("hello world");
}
@GetMapping("/count")
public Result count() {
throw new CustomException("400", "错误!禁止请求");
// return Result.success(10);
}
@GetMapping("/count1")
public Result count1() {
HashMap<String, Object> map = new HashMap<>();
map.put("count", "三明治");
map.put("age", 20);
return Result.success(map);
}
}