SpringBoot全局异常报错处理和信息返回
信息返回类
这种设计可以统一API返回格式,便于前端处理,也便于日志记录和错误排查
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T>
{Integer code;String mes;T data;public static Result success(){return new Result(200,"成功",null);}public static Result error(){return new Result(500,"服务器出现未知错误",null);}public static Result error(String mes){return new Result(500,mes,null);}
}
全局异常处理
全局异常处理可以统一管理异常,避免在每个 Controller 中重复处理异常
自定义异常类
public class MyCustomException extends Exception
{//构造方法public MyCustomException(String message) {super(message);}
}
全局异常处理类
@ControllerAdvice
public class GlobalExceptionHandler
{@ExceptionHandler(Exception.class)@ResponseBodypublic Result handleException(Exception e){//处理自定义异常信息if(e instanceof MyCustomException){//将自定义异常进行转换MyCustomException myCustomException = (MyCustomException)e;return Result.error(myCustomException.getMessage());}//所有异常处理return Result.error(e.getMessage());}
}
控制层
@RestController
@RequestMapping("demo")
public class DemoController
{@GetMapping("getMyCustomException")public String getMyCustomException() throws Exception {throw new MyCustomException("自定义报错信息");}@GetMapping("getException")public String getException() throws Exception{throw new Exception(); }
}
测试结果