好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring中统一异常处理示例详解

前言

系统很多地方都会抛出异常, 而java的异常体系目标就是与逻辑解耦,spring提供了统一的 异常处理 注解,用户只需要在错误的时候提示信息即可

在具体的ssm项目开发中,由于controller层为处于请求处理的最顶层,再往上就是框架代码的。

因此,肯定需要在controller捕获所有异常,并且做适当处理,返回给前端一个友好的错误码。

不过,controller一多,我们发现每个controller里都有大量重复的、冗余的异常处理代码,很是啰嗦。

能否将这些重复的部分抽取出来,这样保证controller层更专注于业务逻辑的处理,

同时能够使得异常的处理有一个统一的控制中心点。

下面话不多说了,来一起看看详细的介绍吧

1. 全局异常处理

1.1. handlerexceptionresolver接口

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

public interface handlerexceptionresolver {

  /**

  * try to resolve the given exception that got thrown during on handler execution,

  * returning a modelandview that represents a specific error page if appropriate.

  * <p>the returned modelandview may be {@linkplain modelandview#isempty() empty}

  * to indicate that the exception has been resolved successfully but that no view

  * should be rendered, for instance by setting a status code.

  * @param request current http request

  * @param response current http response

  * @param handler the executed handler, or {@code null} if none chosen at the

  * time of the exception (for example, if multipart resolution failed)

  * @param ex the exception that got thrown during handler execution

  * @return a corresponding modelandview to forward to,

  * or {@code null} for default processing

  */

  modelandview resolveexception(

  httpservletrequest request, httpservletresponse response, object handler, exception ex);

}

使用全局异常处理器只需要两步:

实现handlerexceptionresolver接口。 将实现类作为spring bean,这样spring就能扫描到它并作为全局异常处理器加载。

在resolveexception中实现异常处理逻辑。

从参数上,可以看到,不仅能够拿到发生异常的函数和异常对象,还能够拿到httpservletresponse对象,从而控制本次请求返回给前端的行为。

此外,函数还可以返回一个modelandview对象,表示渲染一个视图,比方说错误页面。

不过,在前后端分离为主流架构的今天,这个很少用了。如果函数返回的视图为空,则表示不需要视图。

1.2. 使用示例

来看一个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

@component

@slf4j

public class customhandlerexceptionresolver implements handlerexceptionresolver {

  @override

  public modelandview resolveexception(httpservletrequest request, httpservletresponse response, object handler, exception ex) {

  method method = null ;

  if (handler != null && handler instanceof handlermethod) {

   method = ((handlermethod) handler).getmethod();

  }

  log.error( "[{}] system error" , method, ex);

  responsedto response = responsedto.builder()

  .errorcode(errorcode.system_error)

  .build();

  byte [] bytes = json.tojsonstring(response).getbytes(standardcharsets.utf_8));

  try {

   filecopyutils.copy(bytes, response.getoutputstream());

  } catch (ioexception e) {

   log.error( "error" , e);

   throw new runtimeexception(e);

  }

  return new modelandview();

  }

}

逻辑很显然,在发生异常时,将responsedto序列化为json给前端。

1.3. controller局部异常处理

1.3.1. 使用示例

这种异常处理只局部于某个controller内,如:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@controller

@slf4j

@requestmapping ( "/api/demo" )

public class democontroller {

  @exceptionhandler (exception. class )

  @responsebody

  public responsedto<?> exceptionhandler(exception e) {

  log.error( "[{}] system error" , e);

  return responsedto.builder()

  .errorcode(errorcode.system_error)

  .build();

  }

}

所有controller方法(即被requestmapping注解的方法)抛出的异常,会被该异常处理方法处理。 使用上,在controller内部,用@exceptionhandler注解的方法,就会作为该controller内部的异常处理方法。 并且,它的参数中可以注入如webrequest、nativewebrequest等,用来拿到请求相关的数据。 它可以返回string代表一个view名称,也可以返回一个对象并且用@responsebody修饰,由框架的其它机制帮你序列化。

此外,它还能够对异常类型进行细粒度的控制,通过注解可以有选择的指定异常处理方法应用的异常类型:

?

1

@exceptionhandler ({businessexception. class , databaseerror. class })

虽然说全局异常处理handlerexceptionresolver通过条件判断也能做到,

但是使用这种注解方式明显更具有可读性。

1.3.2. 一个问题

刚才说到异常处理函数可以用@responsebody修饰,就像一般的controller方法一样。

然而,非常遗憾的是,如果使用自定义的handlermethodreturnvaluehandler,却不生效。

比如:

?

1

2

3

4

5

6

7

8

@exceptionhandler (exception. class )

@jsonresponse

public responsedto<?> exceptionhandler(exception e) {

  log.error( "[{}] system error" , e);

  return responsedto.builder()

  .errorcode(errorcode.system_error)

  .build();

}

不知道是我的使用姿势不对,还是什么情况?各种google后无果。

所以,目前的解决方案是,如果能够控制@jsonresponse注解相关的定义代码,将处理返回值这部分逻辑抽取出来,然后在异常处理函数中手动调用。

1.4. controlleradvice

1.4.1. 使用示例

刚才介绍的是controller局部的异常处理,用于处理该controller内部的特有的异常处理十分有用。

首先,定义一个存放异常处理函数的类,并使用@controlleradvice修饰。

?

1

2

3

4

5

6

7

8

9

10

11

@controlleradvice (assignabletypes = {globalexceptionhandlermixin. class })

public class exceptionadvice {

  @exceptionhandler (errorcodewrapperexception. class )

  @responsebody

  public responsedto<?> exceptionhandler(errorcodewrapperexception e) {

  if ((errcodeexception.geterrorcode().equals(errorcode.system_error))) {

   log.error(e);

  }

  return responsedto.oferrocodewrapperexception(errcodeexception);

  }

}

@exceptionhanlder修饰的方法的写法和controller内的异常处理函数写法是一样的。

1.4.2. 控制生效的controller范围

注意到,我是这样编写注解的:

?

1

@controlleradvice (assignabletypes = {globalexceptionhandlermixin. class })

它用来限定这些异常处理函数起作用的controller的范围。如果不写,则默认对所有controller有效。

这也是controlleradvice进行统一异常处理的优点,它能够细粒度的控制该异常处理器针对哪些controller有效,这样的好处是:

一个系统里就能够存在不同的异常处理器,controller也可以有选择的决定使用哪个,更加灵活。 不同的业务模块可能对异常处理的方式不同,通过该机制就能做到。 设想一个一开始并未使用全局异常处理的系统,如果直接引入全局范围内生效的全局异常处理,势必可能会改变已有controller的行为,有侵入性。

也就是说,如果不控制生效范围,即默认对所有controller生效。如果控制生效范围,则默认对所有controller不生效,降低侵入性。

如刚才示例中的例子,只针对实现了globalexceptionhandlermixin接口的类有效:

?

1

2

3

4

5

@controller

@slf4j

@requestmapping ( "/api/demo" )

public class democontroller implements globalexceptionhandlermixin {

}

controlleradvice支持的限定范围:

按注解: @controlleradvice(annotations = restcontroller.class) 按包名: @controlleradvice("org.example.controllers") 按类型: @controlleradvice(assignabletypes = {controllerinterface.class, abstractcontroller.class})

2. 总结

以上几种方式是spring专门为异常处理设计的机制。

就我个人而言,由于controlleradvice具有更细粒度的控制能力,所以我更偏爱于在系统中使用controlleradvice进行统一异常处理。

除了用异常来传递系统中的意外错误,也会用它来传递处于接口行为一部分的业务错误。

这也是异常的优点之一,如果接口的实现比较复杂,分多层函数实现,如果直接传递错误码,那么到controller的路径上的每一层函数都需要检查错误码,退回到了c语言那种可怕的[写一行语句检查一下错误码]的模式。

当然,理论上,任何能够给controller加切面的机制都能变相的进行统一异常处理。比如:

在拦截器内捕获controller的异常,做统一异常处理。 使用spring的aop机制,做统一异常处理。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://frapples.github.io/articles/2018-09-01-ecbc.html

查看更多关于Spring中统一异常处理示例详解的详细内容...

  阅读:16次