views:

531

answers:

2

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?

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?

+2  A: 

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.

matt b
+3  A: 

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.

BrennaSoft