1.统一返回格式Result类的设置
因为数值有多种返回类型,并且如果在返回过程中出现错误,那么寻常的包装类就无法展示错误,所以需要设置一个统一的返回形式也就是Result类
首先在我们的org.example下建立一个common包
然后在common中新建Result这个类,并写上如下代码去设置返回的数据
package org.example.springboot.common;
//统一返回的包装类
public class Result {
private String code;
private String msg;
private Object data;
public static Result success(){
Result result = new Result();
result.setCode("200");
result.setMsg("请求成功");
return result;
}
public static Result success(Object data){
Result result = success();
result.setData(data);
return result;
}
public static Result error(){
Result result = new Result();
result.setCode("500");
result.setMsg("请求失败");
return result;
}
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;
}
}
其中code是用来返回状态码,然后msg是针对不同的状态码去写信息,data就是数据,data可以是任何类型的,所以数据类型是Object
2.自定义异常处理
1.全局异常
首先先解释几个注解
@ControllerAdvice
@ControllerAdvice
会扫描所有标注了@Controller
或@RestController
的类。- 它可以结合方法注解(如
@ExceptionHandler
、@ModelAttribute
和@InitBinder
)处理控制器层的异常或数据绑定逻辑。
@ExceptionHandler(Exception.class)
@ResponseBody
@ExceptionHandler(Exception.class)
- 指定当前方法用来处理特定类型的异常,例如
Exception
或其子类。- 捕获到异常后会调用此方法处理,并将其返回值作为响应内容。
@ResponseBody
- 指定方法的返回值是直接作为 HTTP 响应体返回,而不是视图名称。
- 如果返回的是对象,会通过 Spring 的
HttpMessageConverter
序列化为 JSON 格式返回。
@ExceptionHandler经常与@ResponseBody一起使用
@ControllerAdvice("org.example.springboot.controller")
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody //返回json串
public Result error(Exception e){
e.printStackTrace();
return Result.error();
}
}
2.自定义异常
因为有的时候并没有产生异常,但是此时你有想要后台有异常提醒,所以这时候就需要你自己写一个异常类,在出现错误的时候手动抛出
public class CustomException extends RuntimeException {
String code;
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;
}
}
使用
@RestController
public class WebController {
@GetMapping("/hello")
public String hello(){
return "Hello";
}
@GetMapping("/count")
public Result count(){
throw new CustomException("400","禁止访问");
}
}
别忘了在全局异常处理中加上对于自定义异常的捕获
@ExceptionHandler(CustomException.class)
@ResponseBody
public Result error(CustomException e){
e.printStackTrace();
return Result.error(e.getCode(),e.getMsg());
}
以及Result的error重载
public static Result error(String code,String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}