Skip to content
Advertisement

How to customize the internal server error message (error code : 500)

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 :

JavaScript

Service class :

JavaScript

Postman Output :

JavaScript

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:

JavaScript

And the model ErrorInfo:

JavaScript

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement