spring - Error handling on controller SpringMVC -


i developing application in jax-rs , spring mvc. want notify client each time when default error occured 400, 403, 404, 405 , 415.

controller

    @controller     @requestmapping("/customer")     public class customercontroller {          @autowired         customerservice customerservice;          // ........xxxxxx..............xxxxxxx................xxxxxxx.............//               @crossorigin             @requestmapping(value = "/",                              method = requestmethod.get,                              produces = mediatype.application_json_value)             public @responsebody string fetchcustomer() throws jsonprocessingexception {                 return new objectmapper().writevalueasstring(customerservice.fetchallcustomer());             }              // ........xxxxxx..............xxxxxxx................xxxxxxx.............//  }   

client

$http({         method: "get",         contenttype: "application/json",         url: baseurl + '/customer'       }).success(function (response) {         console.log(response);         // can use         console.log(json.stringify(response);       }).error(function (response) {         console.log(response);       }); 

when request service client want send response status code , custom message.

example

when defind method = post on controller , client send request service should return message

error:{      status code: 405,      message:  invalid method       url: error/405 } 

check this out reference.

define method handling specific error scenario , annotate @exceptionhandler. exception in scenario (request method not supported) httprequestmethodnotsupportedexception.class. can create more generic handler methods using throwable, exception etc.

in order prevent duplication of error handling across controllers, 1 convenient way define handlers in single class , use @controlleradvice on that. way, handlers applied controllers.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -