【问题标题】:HandlerExceptionResolver for annotated controller带注释控制器的 HandlerExceptionResolver
【发布时间】:2009-12-02 09:58:41
【问题描述】:

我有注释控制器,其中包含映射在 url 上的几个方法。像这样:

@Controller
public class CategoryController {

@RequestMapping(value = "/addCategories")
public void addCategories(@RequestParam(value = "data") String jsonData) throws ParseException

@RequestMapping(value = "/getNext")
public void getNext(@RequestParam(value = "data") String jsonData) throws ParseException

...

}

方法需要解析 json 请求并执行一些操作。解析请求可能会产生已检查的ParseException,我可以在方法中处理或将throws 添加到其签名中。我更喜欢第二种方法,因为在这种方法中我不想在代码中添加额外的 try/catch。 那么问题是如何为控制器方法配置和编码处理程序?

【问题讨论】:

    标签: spring exception-handling controller


    【解决方案1】:

    您应该查看 @ExceptionHandler 的 spring 文档。

    @Controller
    public class CategoryController {
    
    @ExceptionHandler(ParseException.class)
    public ModelAndView handleParseExc(ParseException ex) {
      //...
    }
    
    @RequestMapping(value = "/addCategories")
    public void addCategories(@RequestParam(value = "data") String jsonData) throws ParseException
    
    
    }
    

    如果您想为所有控制器处理这些异常,或者子类AbstractHandlerExceptionResolver 并在您的 xml 配置中将其声明为 spring mvc bean。

    【讨论】:

    • 如果你想跳过xml配置,或者继承AbstractHandlerExceptionResolver并用@Component注解。
    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 2014-04-17
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2012-06-16
    相关资源
    最近更新 更多