Logging and Exception handling in a micro-service in Java - java

I am working on a microservice which does some calculation based on certain configurations stored in its own data store. The calculations apis are stored via REST APIs. The application is a spring boot application.
Now there are mainly 3 layers in the application :
REST Controller
Service layer
DAO layer - it used spring data.
I am planning to handle the logging and exception handling using below points:
Log each request that the service receives and response or at least
the response if the status is not in 2xx series.
If there are any checked exception in either DAO layer or Service
layer then log them and throw a custom exception derived from
RuntimeException.
Have Several custom exception which should be thrown from Service
layer mainly if we come across scenarios like invalid values, null
values etc.
Have a try catch block in the REST Controller and log the
exception i.e. message along with stacktrace and return the
response accordingly.
So overall idea is to let the RuntimeExceptions propagate all the way to REST Controller where they should be logged and accordingly the response should be sent. Incase of checked exceptions log them in the same method and throw custom exceptions instead.
Please suggest what should be the correct or a good approach for logging exception in such applications.

Write controller advice which will catch all the exceptions & logs the required contents. You may catch exceptions here. I implemented same what you asked here.
*/
/**
* Uncaught exception handler
* #param e - Exception
*/
#ExceptionHandler(Exception.class)
#ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
#ResponseBody
public void handleError(Exception e,HttpServletRequest request, HttpServletResponse response){
logger.error("Exception occured : {}",e);
//logs request & response here
}
Also please check AbstractRequestLoggingFilter described here.
For all custom application specific exeptions create your own custom exception type & handle it with the help of #ExceptionHandler as specified in above code block.

Choose only one place to log the exceptions.
In your design, if an exception occurs in DAO, it will:
Get logged in DAO
Then trigger a runtime exception, which will be caught and logged in controller
Which should then return non-2xx response status via REST, which will trigger logging the response as per your first point
So you'll have either the same information in three places, or you will have the different bits of information regarding a single error scattered in two or three places across the log.
Choose a single place to log the errors, and make sure all relevant info is present at that place (i.e. set the underlying DAO exception as a cause of the runtime exception, and don't forget to log the runtime exception along with its cause).

Related

How to handle exceptions in Spring that are not thrown not on controller level?

My app has a scheduler job that gets some data from the database and then sends a POST request to another server. I need to handle some exceptions, but I cannot use #ControllerAdvice or #ExceptionHandler as there is no controller involved. What's the way to handle exceptions in this case?
You can write your own #Advice to catch all exception.
Check this already answered by #eric-b AOP Exception Handling

What to return to from a REST API when updates fail

I am writing a web application using Spring Boot that frequently updates data on the back end and returns the updated object to reflect the update on the front end.
The question I have is what to return from my methods if the update should fail for some reason.
I am currently returning the object as it was received should it fail but as it stands the state on the front end would not reflect the failure on the back end in the case that it occurs.
I want to return the object to update the state but doing so prevents me from returning a String or HttpStatus indicating a problem doesn't it? Returning the old object doesn't seem a good solution either.
You can throw an exception in this case of failure from your REST controller.
To handle this exception, Spring provides ResponseEntityExceptionHandler callback class with the help of which you can handle the thrown exception and set different headers in the response entity.
So on client-side, you can recognise that some failure is occurred on server side.
You can set HttpStatus as HttpStatus.INTERNAL_SERVER_ERROR and add more details in the body.
The question I have is what to return from my methods if the update should fail for some reason.
You first need to determine whether the error was caused by the client or by the server, then you can determine the most suitable status code to be returned, either in the 4xx or in the 5xx range. See this answer which may give you some insights.
Instead of returning the request request back in the response, you should return a payload that describes what the problem was. Consider, for example, the payload defined in the RFC 7807 along with the application/problem+json media type.
Finally, this answer may give you insights on how to map an exception to a HTTP status code in Spring:
You can map exceptions to responses by annotating an exception class with #ResponseStatus.
It also gives you the possibility to implement a HandlerExceptionResolver or extend one of the existing implementations, such as the AbstractHandlerExceptionResolver.
Another approach would be using a ResponseEntityExceptionHandler annotated with #ControllerAdvice and define the handled exceptions by annotating the implemented method with #ExceptionHandler.

Exception for REST services for invalid input requests

I am currently developing REST services and throwing BadRequestException for all of the following,
1. Path parameter is invalid
2. Query parameter is invalid
4. Input request object has missing attributes
Is there any specific exceptions for each case like InvalidParameterException or so..? Is there any documentation available to learn which exceptions should be thrown on what situations?
I think it's a personal decision and the answer will depend on your needs to have more detailed expceptions or not.
There are two ways to handle errors with JAX-RS:
Throwing a WebApplicationException
That's the approach you are using, which allows you to map exceptions that extend WebApplicationException to HTTP error responses.
I think throwing a BadRequestException is just fine for all the situations mentioned in your question. Just remember adding a detailed message explaining what was wrong.
If you need a more specific exception, you could consider extending the BadRequestException or maybe the ClientErrorException. The new exceptios could encapsulate the message which explains what the problem with the request. It's up to your needs.
For more details on the exceptions provided by the JAX-RS API, have a look at the javax.ws.rs package documentation. If they do not fit your needs, just extend them and create your specific exceptions.
Using an ExceptionMapper
In other cases it may not be appropriate to throw instances of WebApplicationException, or classes that extend WebApplicationException, and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use a custom exception mapping provider.
Consider, for example, you decide to throw an IllegalArgumentException whenever you received an inapropriate value for your query or path parameters. You can create an ExceptionMapper to map the IllegalArgumentException to a response with the 400 status code:
#Provider
public class IllegalArgumentExceptionMapper
implements ExceptionMapper<IllegalArgumentException> {
#Override
public Response toResponse(IllegalArgumentException exception) {
return Response.status(400).entity(exception.getMessage())
.type("text/plain").build();
}
}
For more details, have a look at the Jersey documentation.
All 3 errors sound like client errors, as the client fails to abide by the contract - so I would return a HTTP 400 Bad Request - perhaps with an explanation in the body of the response.
I believe usually you would create separate cases depending on how you would like to handle these errors. For example, you will have 3 different exceptions to represent your errors.
Most frameworks then allow you to install ExceptionMappers. These map your exceptions to an HTTP response code. These are documented and you should follow them:
For example: http://www.restapitutorial.com/httpstatuscodes.html
In your case for example, I would throw IllegalArgumentExceptions for all those 3 cases and install a mapper, mapping this to a 400 response code with potentially some info.
This can be for example important since the client consuming your service will not receive your exceptions anyway, but rather analyse the response code of the request. With a 400, a user will then know that the request was invalid and won't be retried. You can have similar cases for all sorts.
To read about exception mappers, for example with the help of jersey:
https://jersey.java.net/documentation/latest/representations.html
So to your question:
No, I don't believe there is any best-practise on what Exceptions are thrown from your application. Usually REST frameworks don't have specific exception mappers other than a catch-all mapper that will return a 500 (Internal Server Error)
There is however documentation for REST and the HTTP with regards to which responses should be returned for specific use cases. You should try and design your REST endpoint to conform to those standards for maximum reusability and understandability.
I hope that helps,
Artur

Exception Logging with Spring

I have heard that it is possible to log (or do something else) Exceptions with Spring in my web-App, so I don't have to manually insert in every "catch(){}" block the Log-function.
Does anyone have experience with Spring-overall-logging? I just want to get informed when an error appears
ExceptionHandler is the central point for handling unexpected Exceptions that are thrown during the Faces lifecycle. The ExceptionHandler must not be notified of any Exceptions that occur during application startup or shutdown.
See the specification prose document for the requirements for the default implementation. Exceptions may be passed to the ExceptionHandler in one of two ways:
1.)By ensuring that Exceptions are not caught, or are caught and re-thrown.
This approach allows the ExceptionHandler facility specified in section JSF.6.2 to operate on the Exception.
2.)By using the system event facility to publish an ExceptionQueuedEvent that wraps the Exception.
This approach requires manually publishing the ExceptionQueuedEvent, but allows more information about the Exception to be stored in the event. The following code is an example of how to do this.
Global Exception Handler – Exception Handling is a cross-cutting concern, it should be done for all the pointcuts in our application. We have already looked into Spring AOP and that’s why Spring provides #ControllerAdvice annotation that we can use with any class to define our global exception handler.
The handler methods in Global Controller Advice is same as Controller based exception handler methods and used when controller class is not able to handle the exception.
Sample Code
#ExceptionHandler(Exception.class)
public ModelAndView getExceptionPage(Exception e, HttpServletRequest request) {
request.setAttribute("errorMessageObject", e.toString());
return model;
}
** Here we can catch the base exception class Exception.class or any other exception class. Also we can throw and catch our own custom defines exception class.

redirected request when exception throwed

in my application (using spring),
i try to call a method from view using spring exposingBean. and when i try to invoke a method from view, it throw error. i try to catch with HandlerExceptionResolver, but no luck, i think it cannot handled by HandlerExceptionResolver because exception wasn't thrown to controller.
so i try another way to redirect the request when exception thrown. and i think aspect has possibility to do it. is it possible to redirected request when exception thrown from aspect?
As you rightly say, HandlerExceptionResolver will not be invoked when an exception is thrown from inside the view. These resolvers are very specifically targetted at controller exceptions.
Your best options here are to use either a HandlerInterceptor and override the afterCompletion method, which will contain the exception thrown by the view. You may be able to send a redirect from here, dependning on whether or not the response has already been committed by the view.
I don't see how aspects would help you here, either. Not the tool for this job.
However, my advice to you is to stop using exposed bean in your JSP. I realise that it's temptingly convenient, but this is the sort of trouble you get from using it. I advise that your controller assemble all the data required by the view, stick it in the model, and send it to the view. That way, there's less danger of the view triggering an exception, since it already has everything it needs.
Also, if you need to send a redirect, as you do, then you really need to do this before the view starts executing. Otherwise, the view layer may start writing out the HTTP response headers before the exception is thrown. If this happens, then you won't then be able to send a redirect instead - the response is "committed".

Categories