Spring Boot 与 Kotlin Web应用的统一异常处理

547 阅读4分钟
原文链接: mp.weixin.qq.com

做Web应用,请求处理过程中发生错误是非常常见的。 SpringBoot提供了一个默认的映射:  / error ,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容。

选择一个之前实现过的Web应用(chapter11-5-1 )为基础,启动该应用,访问一个不存在的URL,或是修改处理内容,直接抛出异常,如:

  1. @RequestMapping("/hello")

  2. @Throws(Exception::class)

  3. fun hello() {

  4.    throw  Exception("发生错误")

  5. }

注意版本实例修改默认端口,现在为8083,如果想修改为默认的,请修改application.yml文件

  1. server:

  2.  port: 8080

此时,可以看到类似下面的报错页面,该页面就是 SpringBoot提供的默认  error映射页面。

                            
  1. Whitelabel Error Page

  2. This application has no explicit mapping for /error , so you are seeing this as a fallback.

  3. Fri Jan 19 10 :01: 32 CST 2018

  4. There was an unexpected error (type =Internal Server Error , status= 500).

  5. ????

统一异常处理

虽然,Spring Boot中实现了默认的 error映射,但是在实际应用中,上面你的错误页面对用户来说并不够友好,我们通常需要去实现我们自己的异常提示。

下面我们以之前的Web应用例子为基础(chapter11-5-1 ),进行统一异常处理的改造。

创建全局异常处理类:通过使用 @ControllerAdvice定义统一的异常处理类,而不是在每个  Controller中逐个定义。  @ExceptionHandler用来定义函数针对的异常类型,最后将  Exception对象和请求URL映射到  error .html

@ControllerAdvice 注解的类需要增加 @RestController //springboot1.5.7版本,如果不加 这个会报错 jsonErrorHandler

  1. import org.springframework.web.bind.annotation.ControllerAdvice

  2. import org.springframework.web.bind.annotation.ExceptionHandler

  3. import org.springframework.web.bind.annotation.RestController

  4. import org.springframework.web.servlet.ModelAndView

  5. import javax.servlet.http.HttpServletRequest

  6. /**

  7. * Created by http://quanke.name on 2018/1/10.

  8. */

  9. @ControllerAdvice

  10. @RestController //springboot1.5.7版本,如果不加 这个会报错 jsonErrorHandler

  11. class GlobalExceptionHandler {

  12.    @ExceptionHandler(value = Exception::class)

  13.    @Throws(Exception::class)

  14.    fun defaultErrorHandler(req: HttpServletRequest, e: Exception): ModelAndView {

  15.        val mav = ModelAndView()

  16.        mav.addObject("exception", e)

  17.        mav.addObject("url", req.requestURL)

  18.        mav.viewName = "error"

  19.        return mav

  20.    }

  21. }

实现 error.html页面展示:在  templates目录下创建  error .html,将请求的URL和  Exception对象的  message输出。

                                        
  1. <!DOCTYPE html>

  2. <html xmlns:th= "http://www.w3.org/1999/xhtml">

  3. <head lang= "en">

  4.     <meta charset ="UTF-8" />

  5.     <title>统一异常处理</title>

  6. </head>

  7. <body>

  8. <h1> http://quanke.name  Error Handler</h1>

  9. <div th:text= "${url}"></div>

  10. <div th:text= "${exception.message}"></div>

  11. </body>

  12. </html>

启动该应用,访问:http://localhost:8083/hello,可以看到如下错误提示页面。

  1. http://quanke.name Error Handler

  2. http://127.0.0.1:8083/hello

  3. 发生错误

通过实现上述内容之后,我们只需要在 Controller中抛出Exception,当然我们可能会有多种不同的Exception。然后在  @ControllerAdvice类中,根据抛出的具体Exception类型匹配  @ExceptionHandler中配置的异常类型来匹配错误映射和处理。

返回JSON格式

在上述例子中,通过 @ControllerAdvice统一定义不同Exception映射到不同错误处理页面。而当我们要实现RESTful API时,返回的错误是JSON格式的数据,而不是HTML页面,这时候我们也能轻松支持。

本质上,只需在 @ExceptionHandler之后加入  @ResponseBody,就能让处理函数return的内容转换为JSON格式。

下面以一个具体示例来实现返回JSON格式的异常处理。

创建统一的JSON返回对象,code:消息类型,message:消息内容,url:请求的url,data:请求返回的数据

  1. data class ErrorInfo<T>(var code: Int? = null,

  2.                            var message: String? = "",

  3.                            var url: String? = "",

  4.                            var data: T? = null

  5. )

创建一个自定义异常,用来实验捕获该异常,并返回json

  1. /**

  2. * Created by http://quanke.name on 2018/1/11.

  3. */

  4. class QkException(message: String) : Exception(message)

Controller中增加json映射,抛出QkException异常

  1. import name.quanke.kotlin.chaper11_5_3.exception.QkException

  2. import org.springframework.stereotype.Controller

  3. import org.springframework.web.bind.annotation.RequestMapping

  4. /**

  5. * Created by http://quanke.name on 2018/1/10.

  6. */

  7. @Controller

  8. class UserController {

  9.    @RequestMapping("/json")

  10.    @Throws(QkException::class)

  11.    fun json(): String {

  12.        throw QkException("发生错误 json")

  13.    }

  14. }

为QkException异常创建对应的处理

  1. import name.quanke.kotlin.chaper11_5_3.entity.ErrorInfo

  2. import org.springframework.web.bind.annotation.ControllerAdvice

  3. import org.springframework.web.bind.annotation.ExceptionHandler

  4. import org.springframework.web.bind.annotation.RestController

  5. import javax.servlet.http.HttpServletRequest

  6. /**

  7. * Created by http://quanke.name on 2018/1/10.

  8. */

  9. @ControllerAdvice

  10. @RestController //springboot1.5.7版本,如果不加 这个会报错 jsonErrorHandler

  11. class GlobalExceptionHandler {

  12.    @ExceptionHandler(value = QkException::class)

  13.    @Throws(QkException::class)

  14.    fun jsonErrorHandler(req: HttpServletRequest, e: QkException): ErrorInfo<String> {

  15.        val r = ErrorInfo<String>()

  16.        r.message = e.message

  17.        r.code = 1

  18.        r.data = "Some Data"

  19.        r.url = req.requestURL.toString()

  20.        return r

  21.    }

启动应用,访问:http://localhost:8083/json,可以得到如下返回内容:

  1. {

  2.    "code": 1,

  3.    "message": "发生错误 json",

  4.    "url": "http://127.0.0.1:8083/json",

  5.    "data": "Some Data"

  6. }

至此,已完成在Spring Boot中创建统一的异常处理,实际实现还是依靠Spring MVC的注解,更多更深入的使用可参考[Spring MVC]的文档。

参考

  • https://spring.io/guides/gs/serving-web-content/

源码

  • https://github.com/quanke/spring-boot-with-kotlin-in-action/chapter11-5-3

《Spring Boot 与 kotlin 实战》欢迎关注

我的第一个Kotlin应用

使用Spring Boot和Kotlin创建RESTfull API

Spring Boot 与 kotlin 使用Thymeleaf模板引擎渲染web视图

Spring Boot 与 Kotlin使用Freemarker模板引擎渲染web视图


全科龙婷▼升职加薪