Spring Boot REST API异常处理

Spring Boot REST API使用Spring Data JPA数据库异常返回数据如下:

{
  "timestamp":  "2020-12-22T12:07:55.035+00:00",
  "status": 500,
  "error": "Internal Server Error",
  "message": "could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not execute statement",
  "path": "/notebooks"
}

对前端不友好,需要修改为如下返回:

{
  "timestamp": "2020-12-22T12:20:11.514+00:00",
  "status": 500,
  "error": "Internal Server Error",
  "message": "数据库异常",
  "path": "/notebooks"
}

通过自定义ErrorAttributes实现。

代码:

//org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error
//org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes(javax.servlet.http.HttpServletRequest, org.springframework.boot.web.error.ErrorAttributeOptions)
//org.springframework.boot.web.servlet.error.ErrorAttributes#getErrorAttributes(org.springframework.web.context.request.WebRequest, org.springframework.boot.web.error.ErrorAttributeOptions)

import org.springframework.boot.web.error.ErrorAttributeOptions
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.dao.DataAccessException
import org.springframework.web.context.request.WebRequest

@Configuration
class ExceptionConfiguration {
    @Bean
    fun errorAttributes() = object : DefaultErrorAttributes() {
        override fun getErrorAttributes(webRequest: WebRequest, options: ErrorAttributeOptions): MutableMap<String, Any> {
            val error = getError(webRequest)
            val errorAttributes = super.getErrorAttributes(webRequest, options)
            if (error is DataAccessException) {
                errorAttributes["message"] = "数据库异常"
            }
            return errorAttributes
        }
    }
}