SpringBoot全局异常处理
Posted ࿆孤冷༢
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot全局异常处理相关的知识,希望对你有一定的参考价值。
自定义异常类
@EqualsAndHashCode(callSuper = true)
@Data
public class CustomException extends RuntimeException
private Integer code;
public CustomException(String message, Integer code)
super(message);
this.code = code;
public CustomException(ResultCode resultCode)
super(resultCode.getMessage());
this.code = resultCode.getCode();
全局异常类
@Slf4j
@RestControllerAdvice
public class GlobalException
@ExceptionHandler(CustomException.class)
public Result error(CustomException e)
return Result.error().message(e.getMessage()).code(e.getCode());
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result error(MethodArgumentNotValidException e)
log.error(": ", ResultCode.PARAM_ERROR.getMessage(), e.getMessage());
BindingResult bindingResult = e.getBindingResult();
return Result.error(ResultCode.PARAM_ERROR).message(bindingResult.getFieldErrors().get(0).getDefaultMessage());
@ExceptionHandler(BadSqlGrammarException.class)
public Result error(BadSqlGrammarException e)
log.error(": ", ResultCode.BAD_SQL_GRAMMAR.getMessage(), e.getMessage());
return Result.error(ResultCode.BAD_SQL_GRAMMAR);
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result error(HttpMessageNotReadableException e)
log.error(": ", ResultCode.JSON_PARSE_ERROR.getMessage(), e.getMessage());
return Result.error(ResultCode.JSON_PARSE_ERROR);
@ExceptionHandler(Exception.class)
public Result error(Exception e)
e.printStackTrace();
log.error(": ", ResultCode.UNKNOW_REASON.getMessage(), e.getMessage());
return Result.error();
以上是关于SpringBoot全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章