全局拦截处理
快速开始
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
private static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<Long> messageNotReadable(HttpMessageNotReadableException exception){
InvalidFormatException formatException = (InvalidFormatException)exception.getCause();
List<JsonMappingException.Reference> e = formatException.getPath();
String fieldName = "";
for (JsonMappingException.Reference reference :e){
String fieldName = reference.getFieldName();
}
logger.error("参数不匹配"+exception);
return Result.createFailResult(fieldName+"参数类型不匹配");
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public Result<String> all(Exception e){
logger.error("异常:",e);
return Result.createFailResult("请稍后再试");
}
}
@ControllerAdvice
@ControllerAdvice 默认监控所有的 @RequestMapping 方法,也可以对指定过滤的条件:
@ControllerAdvice(annotations = RestController.class)
@ControllerAdvice("org.example.controllers")
@ControllerAdvice(assignableTypes = {ControllerInterface.class, AbstractController.class})