Why is ErrorController not throwing my custom exception class?

Viewed 91

One of my services raises a custom exception (SearchException). The exception is defined as:

@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class SearchException extends Exception {
    private static final long serialVersionUID = 1L;
}    

I then have a ErrorController:

@Controller
public class TVFErrorController implements ErrorController  {


    private static final Logger log = LoggerFactory.getLogger(TVFErrorController.class);


    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Exception e) {
        //do something like logging
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (status!=null){
            log.error("An error occured: status: "+status.toString());
        }
        if (e != null){
            log.error("Exception that occured: "+e.toString());
            e.printStackTrace();
        }
        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

Most of this is working as expected the only issue is the log message describing the exception in the controller always reports a java.lang.Exception not my SearchException.

1 Answers

Most of this is working as expected the only issue is the log message describing the exception in the controller always reports a java.lang.Exception not my SearchException.

I suppose this is happening because of your error handler erasing exception type from SearchException to Exception when it receives it in:

public String handleError(HttpServletRequest request, Exception e)

I think you need to create explicitly error handler to your SearchException

Related