Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC - Dynamic Error Handling Page

Is there a way to handle all possible error codes while still passing the code to my .jsp? Here I have a single error-page passing 404 where it is added to the model. Rather than adding an error-page for every possible error code, is there a better way I can catch the error and pass the code to the controller/jsp file?

Controller

@RequestMapping(value="/error/{code}", method=RequestMethod.GET)
    public String error(@PathVariable("code") String code, Model model)
    {
        model.addAttribute("code", code);
        return "error";
    }

web.xml

<error-page>
    <error-code>404</error-code>
    <location>/error/404</location>
</error-page>
like image 665
Takkun Avatar asked Jan 18 '26 17:01

Takkun


1 Answers

You could register a generic exception resolver in Spring to catch all exceptions and transform into a rendering of your error.jsp.

Using a specialised RuntimeException thrown by your business logic, that has a code member:

public class MyException extends RuntimeException {
    private final Integer errorCode;

    public MyException(String message, Throwable cause, int errorCode) {
        super(message, cause);
        this.errorCode = errorCode;
    }
}

Or rely on existing RuntimeException instances with your code in the exception message.

Extract the code and/or message and set the HttpServletResponse status and ModelAndView accordingly.

For example:

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component(DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
public class GenericHandlerExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
        ModelAndView mav = new ModelAndView("error");

        if (e instanceof MyException) {
            MyException myException = (MyException) e;
            String code = myException.getCode();

            // could set the HTTP Status code
            response.setStatus(HttpServletResponse.XXX);

            // and add to the model
            mav.addObject("code", code);
        } // catch other Exception types and convert into your error page if required

        return mav;
    }
}
like image 141
andyb Avatar answered Jan 20 '26 08:01

andyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!