Reputation: 51
I have actually a problem within my spring-boot application i developed a restful api linked to an s3 bucket i've customized some exceptions but when i run my url to get an object that doesn't exsit in the console i saw this error exception in my console :
2019-07-25 09:06:45.733 ERROR 1 --- [-nio-443-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.amazonaws.services.s3.model.AmazonS3Exception: The specified key does not exist. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey; Request ID: 60E24BCF6860FC66; S3 Extended Request ID: DUEnMWN7YZKug74Q15uHt4Zei3+a7SxTNYzoj99O0YW58WOwvkdM1kwYpcHrGJiTrLkRLOdUL5I=), S3 Extended Request ID: DUEnMWN7YPOAIZADg74Q15uHt4Zei3+a7SxTNYzoj99O0YW58WOwvkdM1kwYpcHrGJiTrLkRLOdUL5I=] with root cause
com.amazonaws.services.s3.model.AmazonS3Exception: The specified key does not exist. (Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey; Request ID: 60E24BCF6860FC66; S3 Extended Request ID: DUEnMWN7YZKug74Q15uHt4ZDFSFSQSDei3+a7SxTNYzoj99O0YW58WOwvkdM1kwYpcHrGJiTrLkRLOdUL5I=)
So my question is how to perform customization to this error in 2 points:
Upvotes: 0
Views: 8523
Reputation: 103
If you want to avoid the exception completely, you can use the Aws s3 api to see if the object exists or not before trying to download it. I think the method is doesObjectExist
. But seems like overkill if you anyway are going to download the file in case it exists.
So you can put a try-catch and if you end up catching AmazonS3Exception then check the status code and do stuff accordingly.
Upvotes: 0
Reputation: 4870
Write custom exception handler to capture your exceptions and do graceful things.
@ControllerAdvice
@RestController
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(AmazonS3Exception.class)
public final ResponseEntity<Object> handleAmazonS3Exception(AmazonS3Exception ex, WebRequest request) {
ApiError apiError = new ApiError(UNPROCESSABLE_ENTITY, ex.getLocalizedMessage(), ex.getErrors());
return new ResponseEntity<>(apiError, UNPROCESSABLE_ENTITY);
}
}
Here, UNPROCESSABLE_ENTITY
is a HttpStatus
(org.springframework.http.HttpStatus
)
Please change the code of method handleAmazonS3Exception(...)
based on your requirement.
Upvotes: 1