Skip to content

Instantly share code, notes, and snippets.

@rponte
Created October 7, 2021 12:35
Show Gist options
  • Select an option

  • Save rponte/3715070f5ed2c0888af953706c29ef5e to your computer and use it in GitHub Desktop.

Select an option

Save rponte/3715070f5ed2c0888af953706c29ef5e to your computer and use it in GitHub Desktop.
Spring Boot: custom and simple exception handler (using the default payload generated by Spring)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import java.time.LocalDateTime;
import java.util.Map;
@RestControllerAdvice
public class CustomExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<?> handleDatabaseErrors(Exception ex, WebRequest request) {
logger.error("Catching an unhandled database exception thrown by a controller: " + ex.getLocalizedMessage(), ex);
Map<String, Object> body = Map.of(
"status", 500,
"error", "Internal Server Error",
"path", request.getDescription(false).replace("uri=", ""),
"timestamp", LocalDateTime.now(),
"message", "Ocorreu um erro interno. Por favor contate o administrador."
);
return ResponseEntity
.internalServerError().body(body);
}
}
@rponte
Copy link
Author

rponte commented May 5, 2022

Since Spring Boot 2.6.x we need to include server errors explicitly, stacktrace etc.

So, configure your application.properties like this:

server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-stacktrace=on_param
server.error.include-exception=false

Or configure your application.yml like this:

server:
  error:
    include-message: always
    include-binding-errors: always
    include-stacktrace: on_param
    include-exception: false    

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment