How to handle exceptions thrown while rendering a view in Spring MVC?

后端 未结 3 1832
失恋的感觉
失恋的感觉 2020-12-05 02:47

I have a Spring MVC application which uses FreeMarker as View technology (But maybe the view technology doesn\'t really matter for my question). I need to intercept all exce

3条回答
  •  無奈伤痛
    2020-12-05 03:21

    Not sure if my solution works with the problem you're having. Ill just post the way i catch my exceptions to ensure no stack trace is show inside the browser:

    I made an AbstractController class with a method that will handle a specific conflict like this:

    public class AbstractController {
    
        @ResponseStatus(HttpStatus.CONFLICT)
        @ExceptionHandler({OptimisticLockingFailureException.class})
        @ResponseBody
        public void handleConflict() {
        //Do something extra if you want
        }
    }
    

    This way whenever an exception occurs the user will see a default HTTPResponse status. (eg. 404 Not Found etc..)

    I extend this class on all my controller classes to make sure errors are redirected to the AbstractController. This way I don't need to use ExceptionHandler on a specific controller but I can add the globally to all my controllers. (by extending the AbstractController class).

    Edit: After another go on your question, I noticed you're getting errors in your view. Not sure if this way will catch that error..

    Hope this helps!!

提交回复
热议问题