I've got a test service I've written that just takes a file title as a parameter, ie testfile.jpg.. all this is doing is throwing my custom exception with a custom exception message. When I use 'testfile' as the parameter, it works fine.. gives 400 error status code. If I use 'testfile.jpg' it doesn't seem to like the extension in there and the error status code comes back as 500 internal error instead.
Anyone know what I can do to fix this? so it displays the correct 400 error status code when using files with the extension in there (ie testfile.jpg)?
The controller:
@ApiOperation("Tests")
@RequestMapping(value = {"/testingURL/{test}"}, method = RequestMethod.GET, produces = {MediaType.IMAGE_PNG_VALUE,MediaType.IMAGE_JPEG_VALUE})
@ResponseBody
public ResponseEntity<byte[]> getTestingURL(@PathVariable String test) throws Exception{
return assetStoreService.test(test);
}
Service method:
public ResponseEntity<byte[]> test(final String test) throws CustomTestException{
if(!test.isEmpty()){
exceptionThrower();
}
TestImage testImage = new TestImage();
return getResponseEntity(testImage);
}
exceptionThrower:
private void exceptionThrower() throws CustomTestException {
throw new CustomTestException("blahbah");
}
CustomTestException.java:
public class CustomTestException extends Exception {
public CustomTestException(String errorMessage) {
super(errorMessage);
}
}
Exception handler:
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ExceptionHandler(CustomTestException.class)
protected ResponseEntity handleCustomTestException (HttpServletRequest request, CustomTestException ex){
request.removeAttribute(
HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
TestError testError = new TestError(HttpStatus.BAD_REQUEST,ex.getMessage(),ex);
return new ResponseEntity<Object>(testError, new HttpHeaders(), testError.getStatus());
}
The bit below, is to remove the accepted return types (images) so it can return the exception json object response:
request.removeAttribute(
HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
This is off part of content negotiations as a best practice. If you still want to use extension try this in application.properties file
spring.mvc.contentnegotiation.favor-path-extension=true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.