I have a REST API written in Java 8 with Spring Boot. It makes calls to a 3rd party service and returns the JSON response to end user.
What is the most efficient way to return appropriate HTTP status codes with description from 3rd party service to end user dynamically. For example 401, 403, 404 etc...
CodePudding user response:
You have to create advice for your rest controller with @RestControllerAdvice annotation this will catch your exceptions and then you can handle all exceptions in this advice. Just debug and see what type of exceptions thrown from 3rd party and handle all of them in advice. Here is the sample
@RestControllerAdvice
public class ProductExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorMessage> handleInvalidArgument(ConstraintViolationException ex, WebRequest webRequest) {
return generateErrorMessage(ex, webRequest);
}
private ResponseEntity<ErrorMessage> generateErrorMessage(Throwable ex, WebRequest request){
ErrorMessage errorMessage = new ErrorMessage.ErrorMessageBuilder()
.statusCode(HttpStatus.BAD_REQUEST.value())
.timeStamp(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now()))
.message(ex.getMessage())
.description(request.getDescription(false))
.build();
return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
}
}