Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot: how to log httpStatus 500 error

I have created a AppErrorController that extends Boot's ErrorController in order to handle status500 errors. The example:

@Controller
public class AppErrorController implements ErrorController {
    private static final Logger LOGGER = LogManager.getLogger(AppErrorController.class);
    private static final String ERROR = "error";
    private static final String ERROR_MESSAGE = "errorMessage";

    @RequestMapping(value = "/error")
    public String error(Exception e, Model model) {
        LOGGER.error("500", e);
        model.addAttribute(ERROR_MESSAGE, "Internal server error");
        return ERROR;
    }

    @Override
    public String getErrorPath() {
        return ERROR;
    }
}

I need the error to be logged. But the problem is that Exception e is always null. How to extract the actual error in order to log it?


ADDED

I have a GlobalExceptionHandler, but it never catches '500' errors

@Component
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger LOGGER = LogManager.getLogger(GlobalExceptionHandler.class);
    private static final String ERROR = "error";

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        LOGGER.error(e);
        return ERROR;
    }
}
like image 949
sva605 Avatar asked Sep 03 '25 14:09

sva605


1 Answers

One way to catch exception from jsp layer is to define your own error-page and point it location to you controller. Then you can extract the actual cause and do with it whatever you like.

web.xml

<error-page>
    <exception-type>java.lang.Throwable</exception-type>
    <location>/error</location>
</error-page>

ErrorController

@Controller
@RequestMapping("/error")
public class ErrorController {

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

    @RequestMapping
    public String ex(HttpServletRequest request) {
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        throwable.printStackTrace(); //print
        log.error(throwable.getMessage(), throwable); // or log
        // or save to db
        return "error"; //and redirect to some user-friendly page
    }
}
like image 78
Bohdan Levchenko Avatar answered Sep 05 '25 15:09

Bohdan Levchenko