信息返回类
这种设计可以统一API返回格式,便于前端处理,也便于日志记录和错误排查
java
@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 中重复处理异常
自定义异常类
java
public class MyCustomException extends Exception
{
//构造方法
public MyCustomException(String message) {
super(message);
}
}
全局异常处理类
java
@ControllerAdvice
public class GlobalExceptionHandler
{
@ExceptionHandler(Exception.class)
@ResponseBody
public Result handleException(Exception e)
{
//处理自定义异常信息
if(e instanceof MyCustomException)
{
//将自定义异常进行转换
MyCustomException myCustomException = (MyCustomException)e;
return Result.error(myCustomException.getMessage());
}
//所有异常处理
return Result.error(e.getMessage());
}
}
控制层
java
@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();
}
}
测试结果