Spring MVC Best Practice Handling Unrecoverable Exceptions In Controller

后端 未结 2 1597
梦毁少年i
梦毁少年i 2020-12-17 06:06

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?<

相关标签:
2条回答
  • 2020-12-17 06:57

    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.

    0 讨论(0)
  • 2020-12-17 07:09

    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 讨论(0)
提交回复
热议问题