Languages
[Edit]
EN

Spring Boot 2 - controller to handle error and display custom response (404 status, etc.)

7 points
Created by:
rmlocerd
302

In this short article, we would like to show how to add custom controller that handles error requests logging them to console under Spring Boot 2.

Example preview:

Errors handling, custom controller in Spring Boot 2.
Errors handling, custom controller in Spring Boot 2.

Note: the below solution was tested under Spring Boot 2.6.1.

 

Add following files to your project:

application.properties file:

...

server.error.path=/error

...

CustomErrorController.java file:

package com.example.controllers;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CustomErrorController implements ErrorController {

    private static final Logger log = LogManager.getLogger(CustomErrorController.class);

    @RequestMapping(value = "${server.error.path}")
    @ResponseBody
    public String getError(HttpServletRequest request) {

        String servletUri = (String) request.getAttribute("javax.servlet.error.request_uri");
        Integer servletStatus = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String servletMessage = (String) request.getAttribute("javax.servlet.error.message");
        Throwable servletException = (Throwable) request.getAttribute("javax.servlet.error.exception");

        if (servletException == null) {
            log.warn("[ERROR]: " + servletStatus + " " + servletUri + " " + servletMessage);
        } else {
            String exceptionMessage = servletException.getMessage();
            log.warn("[ERROR]: " + servletStatus + " " + servletUri + " " + servletMessage + "\n" + exceptionMessage);
        }

        return "Error detected!";  // <--- change it to your custom response
    }
}

Example log:

2021-12-21 02:18:55.793  WARN 3352 --- [0.0-443-exec-10] c.e.c.CustomErrorController  : [ERROR]: 404 /style.css
2021-12-21 02:18:55.793  WARN 3352 --- [.0.0-443-exec-9] c.e.c.CustomErrorController  : [ERROR]: 404 /script.js
2021-12-21 02:18:56.585  WARN 3352 --- [.0.0-443-exec-7] c.e.c.CustomErrorController  : [ERROR]: 404 /logo.png

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join