开发者

Spring MVC Best Practice Handling Unrecoverable Exceptions In Controller

When you have a controller that does logic with services and DAO's that 开发者_如何学Pythonmay throw an unrecoverable exception, what is the best practice in dealing with those method calls?

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?


Don't catch the Exception and allow it to bubble up to a HandlerExceptionResolver.

You can supply a SimpleMappingExceptionResolver in your applicationContext to map certain exception types (or all) to a view name (such as "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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜