javaweb 项目后端针对前端传入参数格式不匹配错误的全局处理
@ControllerAdvice
public class ErrorHandlerConfig extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
if (ex.getCause() instanceof InvalidFormatException) {
InvalidFormatException iex = (InvalidFormatException) ex.getCause();
List<Map<String, String>> errors = new ArrayList<>();
iex.getPath().forEach(reference -> {
Map<String, String> error = new HashMap<>();
error.put(reference.getFieldName(), iex.getOriginalMessage());
errors.add(error);
});
return handleExceptionInternal(ex, errors, new HttpHeaders(), apiError.getStatus(), request);
}
return super.handleHttpMessageNotReadable(ex, headers, status, request);
}
}