Tha*_*Don 10 java spring exception-handling spring-mvc
在设计SpringMVC应用程序时,@ExceptionHandler可以在REST层中使用注释.通过将异常处理卸载到一组半泛型处理程序,这极大地破坏了控制器方法.
我们服务的基本架构是这样的:
[REST API] <==> [应用程序服务] <==> [数据层]
我相信REST层控制器不应直接处理数据层异常,而应仅处理应用程序服务异常.
但是,这意味着我的所有Application Services方法基本上必须如下所示:
public DomainObject getSomeDomainObjectById(String id) {
DomainObject retVal = null;
try {
myDomainDao.getSomeDomainObjectById(id);
} catch (DataLayerExceptionOfSomeSort ex) {
throw translateToAppropriateServiceException(ex);
}
//do some further processing
return retVal;
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这是很多面对面的异常处理,我不在乎.我怎么能解决这个问题?是否有一种简单的方法可以在Application Services层中实现与Rest层中相同的功能?
我的第一个想法是AOP.我对此持开放态度,因为它不会增加很多瑕疵并且易于配置.
一个非常好的方法是使用@ControllerAdvice注释http://docs.spring.io/spring/docs/4.0.6.RELEASE/spring-framework-reference/htmlsingle/#mvc-ann-controller-advice
使用@ControllerAdvice,我能够实现从@ControllerAdvice返回的标准JSON错误对象https://blog.apigee.com/detail/restful_api_design_what_about_errors
为了表示标准错误,我创建了一个标准 api 异常层次结构,其中包含RestApiErrorResourceNotFoundException(RestApiError error)、BadRequestException (RestApiError) .... 等类。
异常是未经检查的,控制器建议捕获所有异常并分类为标准错误消息,然后将其返回给用户。
| 归档时间: |
|
| 查看次数: |
1100 次 |
| 最近记录: |