在Spring Controller中,我配置了一个全局异常处理程序。我为Spring Controller PathVarilable使用了自定义类型(Ip地址类型)。当Spring将传入的字符串转换为IpAddress类型时,将抛出验证异常(自定义)。但是Spring忽略了这些异常,抛出了自己的TypeMismatchException,错误码为400。我想用我自己的错误代码抛出我自己的异常。有什么方法可以覆盖这个行为吗?我尝试从全局异常处理程序抛出自定义异常,但Spring仍然覆盖它。
发布于 2014-12-12 13:58:29
@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);
}
}
}
https://stackoverflow.com/questions/25314948
复制相似问题