在Spring Controller中,我配置了一个全局异常处理程序。我使用Spring Controller PathVarilable的自定义类型(IP地址类型)。当Spring将传入的String转换为IpAddress类型时,将引发验证异常(自定义)。但是Spring忽略了异常并抛出了它自己的TypeMismatchException,错误代码为400。 我想用自己的错误代码抛出自己的异常。有没有办法覆盖这种行为?我尝试从全局异常处理程序中抛出自定义异常,但Spring仍然覆盖它。
答案 0 :(得分:0)
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
public RestResponseEntityExceptionHandler() {
super();
}
// API
// 400
/**
* 自定义类型转换错误
*/
@Override
protected ResponseEntity<Object> handleTypeMismatch(TypeMismatchException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request
.getHeader("X-Requested-With")!= null && request
.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
// 如果不是异步请求
// Apply HTTP status code for error views, if specified.
// Only apply it if we're processing a top-level request.
final String bodyOfResponse = "Illegal Arguments";
return handleExceptionInternal(ex, bodyOfResponse, headers, status, request);
} else {// JSON格式返回
Map<String,Object> bodyOfResponse = new HashMap<String,Object>();
bodyOfResponse.put("message", "Illegal Arguments");
bodyOfResponse.put("code",400);
return handleExceptionInternal(ex, bodyOfResponse, headers, status, request);
}
}
}