简体   繁体   English

Spring MVC最佳实践处理控制器中不可恢复的异常

[英]Spring MVC Best Practice Handling Unrecoverable Exceptions In Controller

When you have a controller that does logic with services and DAO's that may throw an unrecoverable exception, what is the best practice in dealing with those method calls? 如果你的控制器使用服务执行逻辑,而DAO可能会抛出一个不可恢复的异常,那么处理这些方法调用的最佳做法是什么?

Currently an app I'm working on has very lengthy try catch methods that simply err.out exception messages, this doesn't seem very robust and I think that this code smells, is there any cookie cutter best practice for handling this in spring-mvc? 目前我正在研究的应用程序有非常冗长的尝试捕获方法,只是错误的错误消息,这似乎不是非常强大,我认为这个代码闻起来,是否有任何cookie切割器最佳实践处理这在春天 - MVC?

Don't catch the Exception and allow it to bubble up to a HandlerExceptionResolver . 不要捕获异常并允许它冒泡到HandlerExceptionResolver

You can supply a SimpleMappingExceptionResolver in your applicationContext to map certain exception types (or all) to a view name (such as "errorpage"). 您可以在applicationContext中提供SimpleMappingExceptionResolver ,以将某些异常类型(或全部)映射到视图名称(例如“errorpage”)。 Or if you need more complex logic, you can supply your own implementation. 或者,如果您需要更复杂的逻辑,您可以提供自己的实现。

This way your code isn't concerned with Exceptions that it can't handle in the first place, and you can make sure that your users see a nice "Oops something happened, don't worry we're on it" page instead of a stacktrace. 这样你的代码就不会关心它无法处理的异常,并且你可以确保你的用户看到一个很好的“糟糕的事情发生了,不要担心我们在它上面”而不是堆栈跟踪。

Check out the @ExceptionHandler 查看@ExceptionHandler

You can use it like 你可以像使用它一样

@ExceptionHandler(IOException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public void handleExc(IOException ext) {}

That would catch all IOExceptions thrown by the controller method and write out a 500 to the response. 这将捕获控制器方法抛出的所有IOExceptions,并向响应写出500。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM