全局异常处理代码
@RestController
@ControllerAdvice
@Slf4j
public class ExceptionHandlerController {
@ExceptionHandler(ValidException.class)
public RspResult ytExceptionHandler(ValidException e) {
return RspResult.failed(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public RspResult runtimeExceptionHandler(RuntimeException e) {
e.printStackTrace();
log.info("RuntimeException{}", e);
log.error("RuntimeException{}", e);
return RspResult.failed(e.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public RspResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
e.printStackTrace();
log.info("MethodArgumentNotValidException{}", e);
log.error("MethodArgumentNotValidException{}", e);
String[] msg = {"操作失败"};
e.getBindingResult().getFieldErrors().forEach(error -> {
msg[0] = msg[0].concat(",").concat(error.getDefaultMessage());
});
return RspResult.failed(msg[0]);
}
}
接口参数实体类指定字段@NotNull controller方法参数加上注解@Valid校验 即可实现参数校验 加上 自动返回校验message