Consider a scenario where I want to create a record in database with the already existing ID. By doing this, we get “500-internal server error”. But I want to customize the message returned to “Id already exist, Cannot create record”. Below is the my sample existing code: Controller class :
@PostMapping(value = "/plans") public ResponseEntity<ResponseSave> savePostPlanDetails( @Valid @RequestBody(required = true) Plan plan) throws ParseException { String planId = plan.getPlanId(); Integer createdId = planDataService.savePlan(plan, planId); ServiceMessage serviceMessage = ServiceMessage.createCreatedServiceMessage(); return new ResponseEntity<>(ResponseSave.createResponseSave(serviceMessage, createdId), HttpStatus.CREATED); }
Service class :
public Integer savePlan(Plan plan, String planId) throws ParseException { PlanDao findResponse = planDataRepository.findByPlanId(planId); if (findResponse != null) { //This line generate 500 error if create with already existing ID. throw new IllegalArgumentException(PlanSearchEnum.RECORD_ALREADY_EXIST.getValue()); } PlanDao planDao1 = requestToResponseMapper.panToPlanDao(plan); PlanDao saveResponse = planDataRepository.save(planDao1); return saveResponse.getInternalId(); }
Postman Output :
{ "message": { "code": "500", "description": "Unable to process request", "type": "Internal Server Error" } }
As in the above postman response, I want the description to be like : “description”: “Id already exist, Cannot create record” instead of the general message as show above. So how to do this ?
Advertisement
Answer
You will need to have a handler for the exception:
@ControllerAdvice @Slf4j public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(value = {IllegalArgumentException.class}) public ResponseEntity<Object> handleIllegalArgumentExceptions(Exception exception, WebRequest webRequest) { HttpStatus errorCode = HttpStatus.INTERNAL_SERVER_ERROR; return this.handleExceptionInternal(exception, new ErrorInfo(errorCode.value(), "Id already exist, Cannot create record"), new HttpHeaders(), errorCode, webRequest); } }
And the model ErrorInfo
:
public class ErrorInfo { private final int code; private final String description; }
Finally, you should definitely consider creating your own exception instead of using the generic IllegalArgumentException
. You can create something more meaningful for your business case, such as RecordAlreadyExistsException
.