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".
Related
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.
I am using spring boot to make a mock of one of our more complicated services. While all of the standard cases are easily done there is one that is causing me some troubles. It is theoretically possible for the application I am mocking to crash and close the connection without sending a response.
I tried several things to achieve this in spring boot without actually having my mock to crash. This includes throwing exceptions that go into an exception handler and from there do not properly response, however so far that either has generated an error response by spring or somehow resolved to an empty response.
Is there an option to have a method in a #Conroller to cause a closed connection without any response?
Closing the connection is the responsibility of HTTP specification and protocol. You cannot enforce it programmatically. Connection negotitation is happening between HTTP Client and HTTP Server.
Although you can try interrupting current Thread or setting header Connection: close, but you should not be messing around with that part of the processing of a Connection and Request. Your HTTP server can start behaving unexpectedly.
Try a different approach. If you need to simulate a closed connection you can programmatically allocate a new instance of HTTP server, send a request to it, put request processing on hold and kill an instance is a separate thread. I'm sure you'll find a better way for this, just get to the root of the problem from a different angle.
You can create method like this:
#ResponseBody
#RequestMapping("/your-url")
public String test() {
return null;
}
you can also change #Controller to #RestController and remove the #ResponseBody
I am using spring boot to make a mock of one of our more complicated services. While all of the standard cases are easily done there is one that is causing me some troubles. It is theoretically possible for the application I am mocking to crash and close the connection without sending a response.
I tried several things to achieve this in spring boot without actually having my mock to crash. This includes throwing exceptions that go into an exception handler and from there do not properly response, however so far that either has generated an error response by spring or somehow resolved to an empty response.
Is there an option to have a method in a #Conroller to cause a closed connection without any response?
Closing the connection is the responsibility of HTTP specification and protocol. You cannot enforce it programmatically. Connection negotitation is happening between HTTP Client and HTTP Server.
Although you can try interrupting current Thread or setting header Connection: close, but you should not be messing around with that part of the processing of a Connection and Request. Your HTTP server can start behaving unexpectedly.
Try a different approach. If you need to simulate a closed connection you can programmatically allocate a new instance of HTTP server, send a request to it, put request processing on hold and kill an instance is a separate thread. I'm sure you'll find a better way for this, just get to the root of the problem from a different angle.
You can create method like this:
#ResponseBody
#RequestMapping("/your-url")
public String test() {
return null;
}
you can also change #Controller to #RestController and remove the #ResponseBody
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).
For exceptions thrown while handling a request, Spring has a number of different ways to register exception handlers. Is there a way to apply similar exception handling when the exception is thrown while rendering a view? At a minimum I'd like the ability to perform some logging.
The problem is that exceptions thrown during View rendering cannot do an awful lot. In particular, they typically can't render a HTML page containing an error report ... or even send a 5xx response ... because the response will typically have "committed" before the exception is thrown.
So the best you can do (probably) is:
create a wrapper for the View object that catches and logs the exception, or
do the logging in a servlet filter,
But the chances are that the web container can be configured to log uncaught exceptions anyway.
UPDATES
I just noticed spring's HandlerInterceptor class exposes an 'afterCompletion' method which will be invoked when exceptions are thrown. Any thoughts as to the benefits of using this vs. a filter?
Try it and see. :-) But given the following, I doubt that it will work.
Using a filter or interceptor does not work for exceptions thrown while rendering a jsp. It does print to err out:
Dec 16, 2012 12:18:03 PM org.apache.catalina.core.ApplicationDispatcher
invoke SEVERE: Servlet.service() for servlet jsp threw exception
javax.el.PropertyNotFoundException: Property 'fooo' not found on
type java.lang.String"
Unfortunately the exception is not propagated upwards to the filter. I'd like to add my own logging which sends out error notifications and logs additional information about the failed request. Keeping an eye on log files to spot errors isn't a good option.
The chances are that the log message is actually produced using the logging subsystem. If it is, you can use the logging configuration to add your own handler for JSP engine logging events and send out special notifications.
The fact that the exceptions are 1) being thrown during JSP view rendering, and 2) the JSP engine is not propagating them means that (IMO) it is unlikely there is a way for you to catch them.
The other option is to set up a scanner for the log files ... as part of your general system monitoring.