Skip to content

Instantly share code, notes, and snippets.

@MarkusBansky
Created March 4, 2021 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkusBansky/1b89c0031ddedd1540162c161a302482 to your computer and use it in GitHub Desktop.
Save MarkusBansky/1b89c0031ddedd1540162c161a302482 to your computer and use it in GitHub Desktop.
Spring Boot -> REST HTTP Error Handler Config
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(value = HttpClientErrorException.class)
ResponseEntity<ErrorResponse> handleHttpClientErrorException(HttpClientErrorException ex, HttpServletRequest request) {
LOGGER.error("HTTP Client error [{}] happened while calling API endpoint: {}", ex.getStatusCode(), ex.toString());
return new ResponseEntity<>(new ErrorResponse(ex, request.getRequestURI()), ex.getStatusCode());
}
@ExceptionHandler(value = HttpServerErrorException.class)
ResponseEntity<ErrorResponse> handleHttpServerErrorException(HttpServerErrorException ex, HttpServletRequest request) {
LOGGER.error("HTTP Server error [{}] happened while calling API endpoint: {}", ex.getStatusCode(), ex.toString());
return new ResponseEntity<>(new ErrorResponse(ex, request.getRequestURI()), ex.getStatusCode());
}
}
import lombok.Data;
import org.springframework.web.client.HttpStatusCodeException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Data
public class ErrorResponse {
private String timestamp;
/** HTTP Status Code */
private int status;
/** HTTP Reason phrase */
private String error;
/** A message that describe the error thrown when calling the downstream API */
private String message;
/** URI that has been called */
private String path;
public ErrorResponse(HttpStatusCodeException ex, String path) {
this.timestamp = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.now());
this.status = ex.getStatusCode().value();
this.error = ex.getStatusCode().getReasonPhrase();
this.message = ex.getMessage();
this.path = path;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment