error handling – Best way to add the custom exception for the spring boot code

error handling – Best way to add the custom exception for the spring boot code

Here are some of approaches you can follow to handle your custom exceptions.

Create a POJO to handle your custom error messages and put your properties you want to return.

public class ErrorResponse {
     private String message;

     public String getMessage() {
       return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }
}

Approach 1. Within your Controller method.

    @RequestMapping(/car/{id})
    public ResponseEntity<?> getCar(@PathVariable String id) {
        Car car = carService.getCar(id);
        if (car == null) {
          ErrorResponse errorResponse = new ErrorResponse();
          errorResponse.setMessage(Record not found);
          return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND)
         }
       return new ResponseEntity<>(car, HttpStatus.OK); 
    }    

Approach 2: Handle exceptions globally.

Step 1: Create NotFound exception class and extend to RunTime Exception.

public class NoRecordFoundException extends RuntimeException {

    public NoRecordFoundException() {
        super();
    }
}

Step 2: Create Global Exception handler

@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(NoRecordFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ErrorResponse handleNoRecordFoundException(NoRecordFoundException ex) 
{

    ErrorResponse errorResponse = new ErrorResponse();
    errorResponse.setMessage(No Record Found);
    return errorResponse;
}

//same you can handle Exceptionerror for internal

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponse handleDefaultException(Exception ex) {
    ErrorResponse response = new ErrorResponse();
    response.setMessage(ex.getMessage());
    return response;
}
}

Step 3: throw Not found exception from your controller or service:

        @RequestMapping(/car/{id})
        public ResponseEntity<?> getCar(@PathVariable String id) {
            Car car = carService.getCar(id);
            if (car == null) {
             throw new NoRecordFoundException();
             }
           return new ResponseEntity<>(car, HttpStatus.OK); 
        }    

Approach 3: Create @ExceptionHandler within controller and throw

 @ExceptionHandler(NoRecordFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorResponse handleNoRecordFoundException(NoRecordFoundException ex) {

        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setMessage(No Record Found);
        return errorResponse;
    }

The best way to handle any app specific exceptions is to create a custom exception class. Create a package saying com.randomorg.appname.exception. In that create an appexception class that extends the Javas Exception class.

public class CustomAppException extends Exception {

    private String requestId;

    // Custom error message
    private String message;

    // Custom error code representing an error in system
    private String errorCode;

    public CustomAppException (String message) {
            super(message);
            this.message = message;
        }

        public CustomAppException (String requestId, String message, String errorCode) {
            super(message);
            this.requestId = requestId;
            this.message = message;
            this.errorCode = errorCode;
        }

        public String getRequestId() {
            return this.requestId;
        }

        public void setRequestId(String requestId) {
            this.requestId = requestId;
        }

        @Override
        public String getMessage() {
            return this.message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public String getErrorCode() {
            return this.errorCode;
        }

        public void setErrorCode(String errorCode) {
            this.errorCode = errorCode;
        }
    }
}

Once this is done, ensure your controller uses this exception, this way you can customize any exception to become app based.

In your case, your methods like addCar, getCar, you can say it throws CustomAppException and then you can handle it in a simple try catch block.

To improvise further, you can further specialize exception by extending the CustomAppException class, say MyCustomException extends CustomAppException, this way you can organize your exception handling better. Let me know if you need more help on this. Happy to help.

error handling – Best way to add the custom exception for the spring boot code

Leave a Reply

Your email address will not be published. Required fields are marked *