spring - How to handle HttpMediaTypeNotAcceptableException by writing error content to the response body using exception handler annotation? -


when client request resource producing application/json content accept header of application/xml. request fails httpmediatypenotacceptableexception exception , wrapped error message body in response entity object using exception handler annotation mentioned in below code. however, receive httpmediatypenotacceptableexception again when return values written response httpmessageconverter. because checks producible content type response acceptable request type, trying communicate client using error message. how workaround issue ? btw, other exceptions parsing fine error message. please advise.

@controlleradvice     public class restexceptionhandler extends responseentityexceptionhandler {       @override       protected responseentity<object> handleexceptioninternal(exception ex, object body,           httpheaders headers, httpstatus status, webrequest request) {           // setting response content type json           headers.setcontenttype(mediatype.application_json);         return responseentity.status(status).headers(headers).body(body);       }     } 

a few options come mind. 1 controller method produces all content types , throw exception in method if content type not 1 expecting, exception handler can take exception , transform it. 1 works exception handlers, exception handlers only deal exceptions produced in controller method.

the other options are:

  • use interceptor (but i'm not sure if work, spring might try resolve first controller method rather invoking interceptors).
  • extend requestmappinghandlermapping call exception handler if doesn't find suitable method. you'll need override method handlenomatch. in there you'll need reference list of handlerexceptionresolver

the first 1 simplest understand, , latest 1 might 'extensible', requires understanding of internals of spring.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -