How an application which serves resources (.js; .css...) could return JSON entities if an error occurs ?
I wrote a ControllerExceptionHandler
according to this blog:
package com.my.rest;
import com.my.rest.errors.ErrorMessage;
import com.my.rest.errors.ErrorMessageFactory;
import com.my.service.errors.NotFoundException;
import com.my.service.errors.ValidationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@ControllerAdvice
@ResponseBody
public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHandler {
@Autowired
private ErrorMessageFactory messageFactory;
@ResponseStatus(NOT_FOUND)
@ExceptionHandler({NotFoundException.class})
public ResponseEntity<Object> handleServiceException(RuntimeException e, WebRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
return handleExceptionInternal(e, messageFactory.generateMessage(e), headers, HttpStatus.NOT_FOUND, request);
}
}
If the request URL is: https://my-server/resources/a.js
, but a.js
is not found, this ExceptionHandler leads to a HttpMediaTypeNotAcceptableException
thrown by AbstractMessageConverterMethodProcessor
because ContentNegotiationManager
uses a strategy based on the extension .js
, and determines that ErrorMessage
is not applicable to the media type application/javascript
.
My question is: Is there a way to ignore the check of media type to always send JSON error responses so that the client-side error management can parse it ?
Thank you