0

How to log every and any error spring boot 2.6.0 throws? I want to log even when theres a 404 NOT FOUND error. Ive tried the code below but no luck, what am I doing wrong?

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class ErrorController {

    @Autowired
    EmailServiceImpl emailService;

    /**
     * Intercept every error ??
     * @param t
     * @param model
     * @return 
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String exception(final Throwable t, final Model model) {
        String errorMessage = (t != null ? t.getMessage() : "Unknown error");
        model.addAttribute("errorMessage", errorMessage);
        sendEmail(errorMessage);
        
        return "error";
    }

    /**
     * TODO
     */
    private void sendEmail(String errorMessage) {
        emailService.sendSimpleMessage("Erro detectado", errorMessage);
    }

}

References:

Spring Boot REST service exception handling

KenobiBastila
  • 513
  • 2
  • 13
  • 43

0 Answers0