Spring @ExceptionHandler处理多种异常 [英] Spring @ExceptionHandler handling multiple kinds of exceptions

查看:1823
本文介绍了Spring @ExceptionHandler处理多种异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚@ExceptionHandler如何处理一种以上的异常。

I can't figure out how to handle more than one kind of exception by @ExceptionHandler.

我需要以编程方式处理这些异常,为此,我需要共享的引用。这是通过引用 Exception ex完成的吗?我不这么认为,因为没有这样捕获异常,所以我该怎么办?

I need to programmatically deal with these exceptions, for this I'd need a shared reference. Is this done via this reference "Exception ex" ? I don't think so, cause the exception is not caught like this, how would I do it then ?

我不能将所有异常引用都作为参数处理程序方法,这是没有意义的,无法以编程方式进行处理。我需要一个共享的引用,以便可以在其上使用 instanceof,也可以将其作为常规的 Exception发送到其他地方。

I can't put all the exception references as arguments to the handler method, it wouldn't make sense, it can't be programmatically dealt with. I need a shared reference so that I could use "instanceof" on it or just send it somewhere else as a general "Exception"

@ExceptionHandler({DescriptionCstOrderException.class, SpecializationCstOrderException.class, NoUploadFileException.class,
                    DeadLineCstOrderException.class, DocumentCstOrderException.class, CommentCstOrderException.class})
public String handleFormException(Exception ex, ActionRequest actionRequest) {
    logger.error(ex.getMessage());
    SessionErrors.add(actionRequest, ex.getClass().getName());  
    return "mainOrderForm";
  }

其他问题:如果我想处理 org,该怎么办.springframework.web.multipart.MaxUploadSizeExceededException ,不是从处理程序的任何方法抛出的吗?因为 @ExceptionHandler 仅捕获从一种处理程序方法引发的异常。

Additional question: what if I wanted to handle org.springframework.web.multipart.MaxUploadSizeExceededException, that is not thrown from any method of the handler? Because @ExceptionHandler catches only exceptions that are thrown from one of the handler methods.

exceptionHandler 方法可以放在某个扩展的父控制器中,但是如果仅使用 defaultAnnotationHandlerMapping ...?

The exceptionHandler method could be placed into some extended parent controller but if one uses only defaultAnnotationHandlerMapping... ?

感谢任何帮助,我疯了,这真令人沮丧....

Appreciate any help, I'm going crazy, this is very frustrating....

推荐答案

可以将@ExceptionHandler值设置为Exception类型的数组。如果抛出的异常与列表中的一种类型匹配,则将调用以匹配的@ExceptionHandler注释的方法。如果未设置注释值,则使用列为方法参数的异常类型。有关详细信息,请参见文档

The @ExceptionHandler value can be set to an array of Exception types. If an exception is thrown matches one of the types in the list, then the method annotated with the matching @ExceptionHandler will be invoked. If the annotation value is not set then the exception types listed as method arguments are used. See the documentation for details.

这篇关于Spring @ExceptionHandler处理多种异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆