EzyHTTP Handle Exceptions
Updated at 16856862810001. Use default exception
EzHTTP provides to you some default Http exceptions related to HTTP Error codes:
HttpBadRequestException
: 400 - Bad RequestHttpUnauthorizedException
: 401 - UnauthorizedHttpForbiddenException
: 403 - ForbiddenHttpNotFoundException
: 404 - Not FoundHttpMethodNotAllowedException
: 405 - Method Not AllowedHttpNotAcceptableException
: 406 - Not AcceptableHttpRequestTimeoutException
: 408 - Request TimeoutHttpConflictException
: 409 - ConfictHttpUnsupportedMediaTypeException
: 415 - Unsupported Media TypeHttpInternalServerErrorException
: 500 - Internal Server Error
Or you can throw HttpRequestException if you want to response other codes and data. For example, in this case if the book's name length is longer than MAX_NAME_LENGTH, EzyHTTP will return to client Status 400 and message name length must < {max value}:
public void validate(AddBookRequest request) { if (request.getBookName().length() > MAX_NAME_LENGTH) { throw new HttpBadRequestException("name length must < " + MAX_NAME_LENGTH); } }
You can find out full source code in BookValidator example.
2. Handle exception in a controller
If your exception only happends in a controller scope, you should handle it in that controller like this:
@Controller("/api/v1/category") public class CategoryController { // request handler methods @TryCatch(CategoryNotFoundException.class) public ResponseEntity handle(CategoryNotFoundException e) { return ResponseEntity.notFound( Collections.singletonMap("category", "notFound") ); } }
You can find out full source code in CategoryController example.
3. Handle exceptions in a global handler
If your exceptions happend in many controller, and you want to save time and avoid source code duplication, you can create a global handler class to handle that exceptions like this:
@ExceptionHandler public class GlobalExceptionHandler extends EzyLoggable { @TryCatch(IllegalArgumentException.class) public ResponseEntity handleException( IllegalArgumentException e ) { logger.info("invalid argument: {}", e.getMessage()); return ResponseEntity.badRequest(e.getMessage()); } @TryCatch(NotFoundException.class) public ResponseEntity handleException( NotFoundException e ) { logger.info("not found: {}", e.getMessage()); return ResponseEntity.notFound(e.getMessage()); } }
You can find out full source code in GlobalExceptionHandler example.
4. Next
We can intercept client's requests