From b73568fe17500765c33f6a062226e6b433412c49 Mon Sep 17 00:00:00 2001 From: Vitaly Takmazov Date: Wed, 24 Mar 2021 19:01:19 +0300 Subject: Cleanup HttpMediaTypeNotAcceptableException handler * move ExceptionHandler to ControllerAdvice * add test * reindent using VSCode --- src/main/java/com/juick/www/api/Index.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'src/main/java/com/juick/www/api/Index.java') diff --git a/src/main/java/com/juick/www/api/Index.java b/src/main/java/com/juick/www/api/Index.java index bafb6758..2d71683e 100644 --- a/src/main/java/com/juick/www/api/Index.java +++ b/src/main/java/com/juick/www/api/Index.java @@ -18,11 +18,18 @@ package com.juick.www.api; import io.swagger.v3.oas.annotations.Hidden; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.HttpMediaTypeNotAcceptableException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; @@ -30,13 +37,20 @@ import java.net.URI; /** * Created by vitalyster on 25.07.2016. */ +@ControllerAdvice @RestController public class Index { - + private static final Logger logger = LoggerFactory.getLogger("API"); @Hidden @RequestMapping(value = { "/api/", "/ws/" }, method = RequestMethod.GET) public ResponseEntity description() { URI redirectUri = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/swagger-ui.html").build().toUri(); return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).location(redirectUri).build(); } + @ExceptionHandler(HttpMediaTypeNotAcceptableException.class) + public ResponseEntity invalidMediaType(final HttpMediaTypeNotAcceptableException exception, + final NativeWebRequest request) { + logger.info("Media type not resolved ({}) for url: {}", request.getHeaderValues("Accept"), ServletUriComponentsBuilder.fromCurrentRequestUri()); + return ResponseEntity.badRequest().body("Invalid media type"); + } } -- cgit v1.2.3