Home

Monday, August 7, 2023

Spring Boot Rest API -Exception handling

Client is sending the request. Getting response. If everything is okay. Then we are good. But if something fails to work like It supposed to, Then this is part of exception that it throws. What you want to send as a responds when there is an exception?

By default, Spring Boot is imparting a fallback error-handling page, and error-handling response in case of REST requests. Particularly, Spring Boot appears for a mapping for the /error endpoint during the start-up. This mapping depends on what is set on a ViewResolver class. When no legitimate mappings can be found, Spring Boot mechanically configures a default fallback error page. This so-called Whitelabel Error Page is nothing more than a white HTML page containing the HTTP reputation code and a uncertain error message.

This is what the Whitelabel HTML page looks like in your browser:

We need some error code or error message that is sent as JSON and not some random html page that tomcat server throws up right…

There are couple of ways ,we can approach error handling in REST API.

1. We can create an exception and we can throw it if there is no id.
2. Customize Error Response
1. Custom Exception: When you use Spring boot with Rest API then, We have to create a custom exception class like EmployeeNotFoundException.


Let’s first create EmployeeNotFoundException class. and this I want to be as an RuntimeException so iam going to extends RuntimeException, then we have to add Serial id. Because RuntimeException have serial id. Then we create constructor. This constructor takes the String and calls the parent. So actually this exception is thrown when the data we are looking for is not found return employeeRepository.findEmployeeById(id)


Go to POSTMAN. I have addaed 2 employees. Now i wanted to check employee ID which is not existing. When we hit the URL, This is the below response we get when we get for non existing employee.

I don’t want to send status code 500. I want to send 404. For this You can specify the Response Status for a specific exception along with the definition of the Exception '@ResponseStatus' annotation.



Now go to POSTMAN. Hit the send button.You will get below responds.

You got desired result right. This is the way we have to CUstom our Exception in Spring Boot Rest API.

Now let's see Second approarch.

2. Customize error Response:

I don’t want to simply send 404. I want to send specific error message. For that we have to create error response bean class that has date timestamp, string message, string detail and Allargconstructor.

Then create CustomizedResponseEntityExceptionHandler. This class extends ResponseEntityExceptionHandler. In order to get ErrorDetails to return the error response, we have to define a @ControllerAdvice annotation to this class.

• @ExceptionHandler() indicates that this method would handle exceptions of the specific type.
• ResponseEntity(errorDetails, HttpStatus.NOT_FOUND) - Create an error response object and return it with a specific Http Status

Now Hit the send button in POSTMAN. We will get below response.

Related video for this Post:

Tuesday, August 1, 2023

REST API Methods -PUT,POST,PATCH,GET , DELETE

Request from the browser send to the server. And we will get the response from the server. For each and every customer data, we are storing an identifier to find that patron facts and we will send back that identifier to the customer for reference. When we plan the REST APIs, there is lot possibilities that there can be replica requests coming to the API. These duplicate requests can also be accidental as nicely as intentional every now and then (e.g. due to timeout or network issues). We have to make our APIs fault-tolerant in such a way that the duplicate requests do not leave the system unstable.When we talk about duplicate request we have to talk idempotent.

Idempotent ability we will get same end result with a couple of identical request.No count how many times the method has been called. It should not be counted if the approach has been referred to as only once, or ten instances over.. The result should always be the same.In REST API the following HTTP methods are idempotent:
GET, PUT, DELETE, HEAD, OPTIONS, and TRACE methods

and Only POST method is not idempotent.

1. Why POST method is not Idempotent?
POST is used to create a new resource on the server. So when we invoke the identical request N times, we will have N new resources on the server. Duplication is allowed here. So POST is not idempotent.

2. Why PUT method is Idempotent?
PUT is used to update the resource state. If you invoke a PUT method N times, the very first request will replace the resource; the other N-1 requests will simply overwrite the identical useful resource state again and again.

PUT must exchange the existing aid with the new one. This ability we cannot do partial updates. So, if we choose to replace a single area of the resource, we have to send a PUT request containing the whole resource. Hence, PUT is idempotent.

3. Why PATCH method is Idempotent?
PATCH is used for partial modifications to a resource.If the client sends data with an identifier, then it will check whether or not that identifier exists. If the identifier exists, we will replace the replace with the data, else it will throw an exception. Patch request says that we would only send the records that we want to modify without enhancing or effecting different parts of the data. PATCH does partial update.
Ex: if we need to update only the last name, you can pass only the last name.

4. Difference between PUT and PATCH method
PUT is an Idempotent:
1. PUT should replace the present useful resource with the new one.
2. In PUT method, we are now not throwing an exception if an identifier is not located

PATCH is Idempotent:
1. While PUT is used to replace an existing resource, PATCH is used to apply partial modifications to a resource.
2. In PATCH method, we are throwing an exception if the identifier is not found.

5. Why GET method is Idempotent?
GET is the simplest kind of HTTP request method; the one that browsers use each time you click a link or kind a URL into the address bar. It instructs the server to transmit the information identified by means of the URL to the client. Data need to never be modified on the server side as a result of a GET request. Means, a GET request is read-only

6. DELETE method is Idempotent
DELETE method is pretty easy to understand. It is used to delete a resource identified by a URI.On successful deletion, return HTTP status 200 (OK).

Spring Boot Rest API -Exception handling

Client is sending the request. Getting response. If everything is okay. Then we are good. But if something fails t...