How To Handle Exceptions In Spring REST Web Service

exception handling in spring rest

Here We can Learn, how to handle Exceptions in Spring – Rest

Required Dependencies:

Type Of Exception Handlings in Spring-Rest

In Spring – Rest We Can Handle Exceptions By 4 Ways
  1. Using ResponseEntity Class.
  2. Using @ResponseStatus Annotation
  3. Using @ExceptionHandler Annotation.
  4. Return Error Representation instead of default HTML error Page.

Using ResponseEntity Class

Before Learning Exception hanbling using ResponseEntity , we sholud have clarity on


  • ResponseEntity is a Class from org.springframework.http Package, extends HttpEntity
    (we can call it as helper object).
  • It is Similar to ResponseBody Annotation but, we can add Response Header to HTTP

Now let’s jump into our concept

Here we can use ResponseEntity along with HttpStatusCodes.
Without using ResponseEntity:

• If we are not using ResponseEntity then, if any Exception raised we can directly Re-
direct to Default 500 HttpStatusCode Error Page.

• So, here we can’t get any information about Which Exception Raised at Serverside
• So, for proper Exception Information purpose we are going to use ResponseEntity.
With ResponseEntity:
• We already know about ResponseEntity, by using ResponseEntity we can Transsfer not
only Reponse , we can transfer HttpStatus Codes.
• So, here instead of 500 HttpStatusCode , We can throw 404 Exception. 404 have proper
menaing that is “ Resource Not Found Exception”
• So, for that we have to use ResponseEntity with 2 Arguments.
1 . Returning Object
2 . HttpStatusCode
EmployeeNotFoundException using ResponseEntity:

@RequestMapping(value=“getEmp”, method=RequestMethod.GET,
produces=”application/json” )
public ReponseEntity<?> getEmployeeByEmpId(@RequestParam(“empId”) String

HttpServletRequest req){
EmployeeDtls obj = new EmployeeDtls();
obj = employeeService.getEmployeeDtlsByEmpId(empId);
}catch(EmployeeDtlsNotFoundException e){
return new ResponseEntity<EmployeeDtls>(HttpStaus.NOT_FOUND);
return new ResponseEntity<EmployeeDtls>(obj , HttpStaus.OK);

Note: If We use ReposeEntity for ExceptionHandling in Spring Rest, it adds more linse of code in our Controller . Then it will be look like more complex b’Coz of more try , catch blocks.

Using @ResponseStatus Annotation:

  • ResponseStatus is another way to handling Exception in Spring – Rest.
  • Before using @ResponseStatus Annotation , we need to create custom Exception class. Here, i have created EmployeeDtlsNotFoundExceptionclass.
  • Later, we need to use @ResponseStatus on top of Custom Exception Class. Like below,
   public class EmployeeDtlsNotFoundException extends Exception{
       // class Body 
  • @ResponseStatus Annotation requires 2 arguments,
    • HttpStatusCode .
    • Reason : custom message we can write.
@ResponseStatus(value=”HttpStatus.NOT_FOUND”, reason=” Employee Record Not Found”)
public class EmployeeDtlsNotFoundException extends Exception{
// Body Not Required


Using @ExceptionHandler Annotation:

  • @ExceptionHandler Annotation is another way to handle the Exceptions in Spring-Rest.
  • Basically @ExceptionHandler Annotation used in Custom Methods. In that method we can handle Exception .
  • This Annotation we can use in 2 Ways

    1 . @ExceptionHandler With @ResponseStatus :

    • @ExceptionHandler Requeries one argument that is Custom Exception or Exception class.
    • We already know , @ReponseStatus requires 2 arguments those are HttpStatusCode and Reason.

    How to use on custom method?

    @ResponseStatus(value=”HttpStatus.NOT_FOUND”, reason=” Employee Record Not Found”)
    @ExceptionHandler(EmployeeDtlsNotFoundException .class)
    public void customExceptionHandler(){
    // Body Not Required

    Explanation: if EmployeeDtlsNotFoundException raises this custom method will be hits. The reason written in @ResponseStatus will be sent to client side.

    2 . Only With @ExceptionHandler :

    • We can use Only , @ExceptionHandler Annotation To Handle Exceptions in Spring-Rest.
    • But, if you use only @ExceptionHandler you need to create method body means exception body and send it client. Like below
    @ExceptionHandler(EmployeeDtlsNotFoundException .class)
    public ResponseEntity<?> customExceptionHandler(HttpServletRequest req, Exception e){
    JOSNObject obj = new JSONObject();
    obj.put(“ msgTxt”,” Employee Record Not Found”);
    obj.put(“reqUrl”, e.getRequestURI());
    obj.put(“stackTrace”, e.getMessage());
    obj.put(“httpStatusCode”, HttpStatus.OK.value());
    return ResponseEntity<JSONObject>(obj,HttpStatus.NOT_FOUND);

    Write a comment