
Let’s see how we can define our own custom error and exception handling exceptions in Spring Rest.
Custom Error:
Kindly take a look into the below example.
@ControllerAdvice
public Class AppExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {Exception.class})
public ResponseEntity<Object> handleAnyException(Exception ex, WebRequest request){
String errMsg = ex.getLocalizedMessage(); \\line 4
if (errMsg==null){ \\line 5
errMsg = ex.toString(); \\line 6
}
ErrorMessage em = new ErrorMessage(new Date(), errMsg); \\line 7
return new ResponseEntity<>(
em,new HttpHeaders(), HttpsStatus.INTERNAL_SERVER_ERROR);\\line 8
}
}
As seen above we are using ErrorMessage object at line 7 to set the custom error message.
While sending the response at Line 8, we are adding the ErrorMessage object as the first param and sending the response.
Specific Exception:
Consider the below Rest Controller method.
@RestController
@RequestMapping("employees")
public Class EmpController{
@GetMapping(path="/{empId}",produces = {MediaType.APPLICATION_JSON_VALUE})
public String getEmployee(@PathVariable String empId)
{
String empName = null; \\Line 4
int length = empName.length(); \\Line 5
System.out.println("EmpID fetched VIA get request is "+empId); \\Line 5
}
}
As per above, line 5 would result in an NullPinterException.
Here, we will have a dedicated method in the Exception Class to handle a NullPointerException.
@ControllerAdvice
public Class AppExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {NullPointerException.class}) \\Line 2
public ResponseEntity<Object> handleNullPException(NullPointerException ex, WebRequest request){
String errMsg = ex.getLocalizedMessage();
if (errMsg==null){
errMsg = ex.toString();
}
ErrorMessage em = new ErrorMessage(new Date(), errMsg);
return new ResponseEntity<>(
em,new HttpHeaders(), HttpsStatus.INTERNAL_SERVER_ERROR);
}
}
As per above at line 2, we define the exception handler to handle Null PE.
@ExceptionHandler(value = {NullPointerException.class}) \\Line 2
So once the exception occurs, the above method the exception handler class for controller would automatically catch it and send the repsonse