接着上一篇《springmvc 通过异常增强返回给客户端统一格式》讲通过spring ControllerAdvice对各种异常进行拦截处理,统一格式返回给客户端。
接下来我们更精细的讲,通过@ExceptionHandler拦截异常,提示参数客户端哪些参数没有传或参数数据类型不一致,方便客户端服务端联调测试。
简述一下上一篇拦截异常主要流程:
1.自定义一个类RestExceptionHandler,并使用@ControllerAdvice注解,表示这个类是控制器增强;
2.在RestExceptionHandler新建一个方法,并使用@ExceptionHandler({Exception.clss})注解在方法上,表示这个方法处理异常信息。
3.在springMvc.xml里配置
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />
@ExceptionHandler注解允许我们指定异常类型进行拦截处理,也可以对自定义异常拦截。
那么我们来看看机springmvc对于http请求的异常类型。
Exception Type | HTTP Status Code |
ConversionNotSupportedException | 500 (Internal Server Error) |
HttpMediaTypeNotAcceptableException | 406 (Not Acceptable) |
HttpMediaTypeNotSupportedException | 415 (Unsupported Media Type) |
HttpMessageNotReadableException | 400 (Bad Request) |
HttpMessageNotWritableException | 500 (Internal Server Error) |
HttpRequestMethodNotSupportedException | 405 (Method Not Allowed) |
MissingServletRequestParameterException | 400 (Bad Request) |
NoSuchRequestHandlingMethodException | 404 (Not Found) |
TypeMismatchException | 400 (Bad Request) |
springmvc内部已经为我们定义好了http请求常见的异常类型,我们只需要使用@ExceptionHandler({MissingServletRequestParameterException.class})注解在方法上,方法参数类型就是我们指定的异常类型,就能获取到缺少参数异常时的异常对象。
//参数类型不匹配
//getPropertyName()获取数据类型不匹配参数名称
//getRequiredType()实际要求客户端传递的数据类型
@ExceptionHandler({TypeMismatchException.class})
@ResponseBody
public String requestTypeMismatch(TypeMismatchException ex){
ex.printStackTrace();
return outputJson(-400, "参数类型不匹配,参数" + ex.getPropertyName() + "类型应该为" + ex.getRequiredType());
}
//缺少参数异常
//getParameterName() 缺少的参数名称
@ExceptionHandler({MissingServletRequestParameterException.class})
@ResponseBody
public String requestMissingServletRequest(MissingServletRequestParameterException ex){
ex.printStackTrace();
return outputJson(-400, "缺少必要参数,参数名称为" + ex.getParameterName());
}
这样不管是参数异常,还是数据类型异常,还是请求方法异常,都能做到精细的处理,精确到某个方法的参数和数据类型,给客户端提示更有意义的信息。