- 1、首先创建CustomException继承RuntimeException,使用时可以throw抛出
public class CustomException extends RuntimeException{
private Integer code;
private String message;
public CustomException(Integer code, String message) {
super();
this.code = code;
this.message = message;
}
}
- 2、然后创建ExceptionController(注解@RestControllerAdvice),并添加handleCustomException方法(注解@ExceptionHandler),使CustomException异常抛出使调用该函数,并把结果以JSON形式返回到响应体中(注解@ResponseBody)
@RestControllerAdvice
public class ExceptionController {
@ExceptionHandler(CustomException.class)
@ResponseBody
public CommonResult<Message> handleCustomException(CustomException ex,HttpServletRequest request,HttpServletResponse response){
return CommonResult.failed(ex.getCode(), Message.createMessage(ex.getMessage()));
}
}
throw new CustomException(1001, "用户名或密码错误");