runtimeexceptionn in runtimeexceptionn handler 怎么解决

ExceptionHandler (Spring Framework 5.0.3.RELEASE API)
JavaScript is disabled on your browser.
Spring Framework
Annotation Type ExceptionHandler
@Target(value=METHOD)
@Retention(value=RUNTIME)
@Documented
public @interface ExceptionHandler
Annotation for handling exceptions in specific handler classes and/or
handler methods.
Handler methods which are annotated with this annotation are allowed to
have very flexible signatures. They may have parameters of the following
types, in arbitrary order:
An exception argument: declared as a general Exception or as a more
specific exception. This also serves as a mapping hint if the annotation
itself does not narrow the exception types through its .
Request and/or response objects (typically from the Servlet API).
You may choose any specific request/response type, e.g.
Session object: typically .
An argument of this type will enforce the presence of a corresponding session.
As a consequence, such an argument will never be null.
Note that session access may not be thread-safe, in particular in a
Servlet environment: Consider switching the
flag to "true" if multiple requests are allowed to
access a session concurrently.
Allows for generic request parameter access as well as request/session
attribute access, without ties to the native Servlet API.
Locale for the current request locale
(determined by the most specific locale resolver available,
i.e. the configured
in a Servlet environment).
InputStream / Reader for access
to the request's content. This will be the raw InputStream/Reader as
exposed by the Servlet API.
OutputStream / Writer for generating
the response's content. This will be the raw OutputStream/Writer as
exposed by the Servlet API.
as an alternative to returning
a model map from the handler method. Note that the provided model is not
pre-populated with regular model attributes and therefore always empty,
as a convenience for preparing the model for an exception-specific view.
The following return types are supported for handler methods:
A ModelAndView object (from Servlet MVC).
object, with the view name implicitly
determined through a .
A Map object for exposing a model,
with the view name implicitly determined through a
A String value which is interpreted as view name.
annotated methods (Servlet-only)
to set the response content. The return value will be converted to the
response stream using
(Servlet-only) to set response headers and content. The ResponseEntity body
will be converted and written to the response stream using
void if the method handles the response itself (by
writing the response content directly, declaring an argument of type
for that purpose) or if the view name is supposed to be implicitly determined
(not declaring a response argument in the handler method signature).
In Servlet environments, you can combine the ExceptionHandler annotation
with , to define the response status
for the HTTP response.
Arjen Poutsma, Juergen Hoeller
Optional Element Summary
Optional Elements&
Modifier and Type
Optional Element and Description
java.lang.Class&? extends java.lang.Throwable&[]
Exceptions handled by the annotated method.
Element Detail
public abstract&java.lang.Class&? extends java.lang.Throwable&[]&value
Exceptions handled by the annotated method. If empty, will default to any
exceptions listed in the method argument list.
Spring Framework下次自动登录
现在的位置:
& 综合 & 正文
SPRING MVC3.2案例讲解–异常处理
SPRING MVC 异常处理 可以全局进行定义,也可以单独在SPRING controller中定义;同时SPRING MVC将异常处理的代码和业务逻辑进行分离,将异常的处理放到一个单独的带有@ExceptionHandler方法中;
@Controller
public class ExceptionController {
@RequestMapping("/exception")
public @ResponseBody String exception() {
throw new IllegalStateException("Sorry!");
// 处理异常的代码,这样就实现了业务逻辑和异常处理的分离
@ExceptionHandler
public @ResponseBody String handle(IllegalStateException e) {
return "IllegalStateException handled!";
@RequestMapping("/global-exception")
public @ResponseBody String businessException() throws BusinessException {
throw new BusinessException();
SPRING 处理异常的流程:
1.WEB启动时ExceptionHandlerExceptionResolver 扫描到通用的异常处理方法:
DEBUG ExceptionHandlerExceptionResolver Looking for exception mappings: WebApplicationContext for namespace 'appServlet-servlet': startup date [Sat Jun 08 08:40:41 GMT 2013]; parent: Root WebApplicationContext
ExceptionHandlerExceptionResolver Detected @ExceptionHandler methods in globalExceptionHandler
2.当请求出现异常时,首先看当前类中是否含有@ExceptionHandler的处理方法
DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.exception()]: java.lang.IllegalStateException: Sorry!
DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.handle(java.lang.IllegalStateException)
DEBUG RequestResponseBodyMethodProcessor Written [IllegalStateException handled!] as "text/charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@163e9a1]
3.然后看有没有含有@ExceptionHandler method 的类,另外该类必须@ControllerAdvice
DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.businessException() throws org.springframework.samples.mvc.exceptions.BusinessException]: org.springframework.samples.mvc.exceptions.BusinessException
DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.GlobalExceptionHandler.handleBusinessException(org.springframework.samples.mvc.exceptions.BusinessException)
【上篇】【下篇】他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)他的最新文章
他的热门文章
您举报文章:
举报原因:
原文地址:
原因补充:
(最多只允许输入30个字)Exception handler in Spring MVC - Stack Overflow
Join Stack Overflow to learn, share knowledge, and build your career.
or sign in with
I want to create an exception handler which will intercept all controllers in my project. Is that possible to do? Looks like I have to put a handler method in each controller. Thanks for your help. I have a spring controller that sends Json response. So if an exception happens I want to send an error response which can be controlled from one place.
21.5k19102155
(I found a way to implement it in Spring 3.1, this is described in the second part of this answer)
See chapter
of Spring Reference
There are some more ways than using @ExceptionHandler (see )
You could implement a
(use the servlet not the portlet package) - that is some kind of global @ExceptionHandler
If you do not have a specific logic for the exception, but only specifc view then you could use the , which is at least an implementation of the HandlerExceptionResolver where you can specify an Exception name pattern and the view (jsp) which is shown when the exception is thrown. For example:
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
p:defaultErrorView="uncaughtException"&
&property name="exceptionMappings"&
&prop key=".DataAccessException"&dataAccessFailure&/prop&
&prop key=".TypeMismatchException"&resourceNotFound&/prop&
&prop key=".AccessDeniedException"&accessDenied&/prop&
&/property&
In Spring 3.2+ one can annotate a class with @ControllerAdvice, all @ExceptionHandler methods in this class work in a global way.
In Spring 3.1 there is no @ControllerAdvice. But with a little hack one could have a similar feature.
The key is the understanding of the way @ExceptionHandler works. In Spring 3.1 there is a class . This class implements (with help of its superclasses) the interface
and is responsible invoking the @ExceptionHandler methods.
The HandlerExceptionResolver interface has only one Method:
ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex);`.
When the request was handled by a Spring 3.x Controller Method, then this method (represented by org.springframework.web.method.HandlerMethod) is the handler parameter.
The ExceptionHandlerExceptionResolver uses the handler (HandlerMethod) to obtain the Controller class and scan it for methods annotated with @ExceptionHandler. If one of this methods matches the exception (ex) then this methods get invoked in order to handle the exception. (else null get returned in order to signal that this exception resolver feels no responsible).
The first idea would be to implement an own HandlerExceptionResolver that behaves like ExceptionHandlerExceptionResolver, but instead of search for @ExceptionHandler in the controller class, it should search for them in one special bean. The drawback would be, that one has to (copy (or subclass ExceptionHandlerExceptionResolver) and must) configure all nice message converters, argument resolvers and return value handlers by hand (the configuration of the real one and only ExceptionHandlerExceptionResolver is done by spring automatically). So I came up with an other idea:
Implement a simple HandlerExceptionResolver that "forwards" the exception to THE (already configured) ExceptionHandlerExceptionResolver, BUT with an modified handler which points to the bean that contains the global Exception handlers. (I call them global, because the work for all controllers.).
And this is the implementation: GlobalMethodHandlerExeptionResolver
import java.util.L
import java.util.concurrent.ConcurrentHashM
import java.util.concurrent.ConcurrentM
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
import org.springframework.beans.factory.NoSuchBeanDefinitionE
import org.springframework.beans.factory.annotation.A
import org.springframework.core.O
import org.springframework.util.StringU
import org.springframework.web.method.HandlerM
import org.springframework.web.servlet.HandlerExceptionR
import org.springframework.web.servlet.ModelAndV
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionR
public class GlobalMethodHandlerExeptionResolver
implements HandlerExceptionResolver, Ordered {
public int getOrder() {
return -1; //
private ExceptionHandlerExceptionResolver realExceptionR
private List&GlobalMethodExceptionResolverContainer&
@Autowired
public GlobalMethodHandlerExeptionResolver(
ExceptionHandlerExceptionResolver realExceptionResolver,
List&GlobalMethodExceptionResolverContainer& containers) {
this.realExceptionResolver = realExceptionR
this.containers =
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) {
for (GlobalMethodExceptionResolverContainer container : this.containers) {
ModelAndView result = this.realExceptionResolver.resolveException(
handlerMethodPointingGlobalExceptionContainerBean(container),
if (result != null)
// we feel not responsible
protected HandlerMethod handlerMethodPointingGlobalExceptionContainerBean(
GlobalMethodExceptionResolverContainer container) {
return new HandlerMethod(container,
GlobalMethodExceptionResolverContainer.class.
getMethod("fakeHanderMethod"));
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(e);
The global Handler has to implement this interface (in order to get found and to implement the fakeHanderMethod used for the handler
public interface GlobalMethodExceptionResolverContainer {
void fakeHanderMethod();
And example for an global Handler:
@Component
public class JsonGlobalExceptionResolver
implements GlobalMethodExceptionResolverContainer {
public void fakeHanderMethod() {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDto handleMethodArgumentNotValidException(
MethodArgumentNotValidException validationException,
Locale locale) {
/* map validationException.getBindingResult().getFieldErrors()
* to ValidationErrorDto (custom class) */
return validationErrorD
BTW: You do not need to register the GlobalMethodHandlerExeptionResolver because spring automatically register all beans that implements HandlerExceptionResolver for exception resolvers. So a simple &bean class="GlobalMethodHandlerExeptionResolver"/& is enough.
82.1k34211313
Since Spring 3.2 you can use
annotation.
You can declare an
method within an @ControllerAdvice class
in which case it handles exceptions from @RequestMapping methods
from all controllers.
@ControllerAdvice
public class MyGlobalExceptionHandler {
@ExceptionHandler(value=IOException.class)
public @ResponseBody String iOExceptionHandler(Exception ex){
// other exception handler methods
An abstract class where you define the exception handlers will do. And then make your controllers inherit it.
3,71221318
Your Answer
Sign up or
Sign up using Google
Sign up using Facebook
Post as a guest
Post as a guest
By posting your answer, you agree to the
Not the answer you're looking for?
Browse other questions tagged
Stack Overflow works best with JavaScript enabled

我要回帖

更多关于 exception in thread 的文章

 

随机推荐