天天看点

JAVA入门[17]-ControllerAdvice处理exception

@ControllerAdvice注解本身已经使用了@Component,因此@ControllerAdvice注解所标注的类将会自动被组件扫描获取到,就像带有@Component注解的类一样。另外,在带有@ControllerAdvice注解的类中,异常处理会应用到所有控制器中带有@RequestMapping注解的方法上。

自定义exception:

<code>@ResponseStatus</code><code>(value = HttpStatus.NOT_FOUND,reason = </code><code>"file not found"</code><code>)</code>

<code>public</code> <code>class</code> <code>NotFoundException </code><code>extends</code> <code>RuntimeException {</code>

<code>}</code>

  

定义ControllerAdvice

<code>@ControllerAdvice</code>

<code>public</code> <code>class</code> <code>GlobalExceptionHandler {</code>

<code>    </code><code>@ExceptionHandler</code><code>(NotFoundException.</code><code>class</code><code>)</code>

<code>    </code><code>public</code> <code>String NotFoundHandler()</code>

<code>    </code><code>{</code>

<code>        </code><code>return</code> <code>"error/404.html"</code><code>;</code>

<code>    </code><code>}</code>

<code>    </code><code>@ExceptionHandler</code><code>(Exception.</code><code>class</code><code>)</code>

<code>    </code><code>public</code> <code>String ErrorHandler(){</code>

<code>        </code><code>return</code> <code>"error/error.html"</code><code>;</code>

错误页controller

<code>@RequestMapping</code><code>(</code><code>"/error404"</code><code>)</code>

<code>    </code><code>public</code> <code>String error(){</code>

<code>        </code><code>throw</code> <code>new</code> <code>NotFoundException();</code>

<code>    </code><code>@RequestMapping</code><code>(</code><code>"/error"</code><code>)</code>

<code>    </code><code>public</code> <code>String errorNotFound() </code><code>throws</code> <code>Exception {</code>

<code>        </code><code>throw</code> <code>new</code> <code>Exception();</code>

view:

在views/error目录下新增error.html和404.html

http://localhost:8092/category/error404

http://localhost:8092/category/error

<a href="http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/" target="_blank">http://viralpatel.net/blogs/spring-mvc-exception-handling-controlleradvice-annotation/</a>

    本文转自 陈敬(Cathy) 博客园博客,原文链接:http://www.cnblogs.com/janes/p/6933958.html,如需转载请自行联系原作者