Spring MVC实现REST API 之全局异常统一处理

全局异常统计处理

定义请求出错时候返回的错误信息

class RestErrorBody {
    var status: String = ""
    var error: String = ""
    var message: String = ""

    constructor(status: String, error: String) {
        this.status = status
        this.error = error
    }

    constructor(status: String, error: String, message: String) {
        this.status = status
        this.error = error
        this.message = message
    }
}

全局捕获异常

@ControllerAdvice
class GlobalExceptionHandler {
    private val logger = LoggerFactory.getLogger(this::class.java)
    @ExceptionHandler
    @ResponseBody
    internal fun handleException(e: Exception, response: HttpServletResponse): Any {
        logger.error("unknown", e)
        response.status = 400
        if (e is CredentialNotFoundException){
            response.status = 401
            response.addHeader("WWW-Authenticate","Basic realm=\"oauth2/client\"")
            return RestErrorBody("not_found", e.message)
        }
        else if (e is CredentialException){
            response.status = 401
            // 浏览器弹出需要输入授权信息对话框,方便在浏览器进行测试
            response.addHeader("WWW-Authenticate","Basic realm=\"oauth2/client\"")
        }
        else if (e is MethodArgumentTypeMismatchException) {
            return RestErrorBody("unknown", "参数格式错误", e.message)
        } 
        return RestErrorBody("unknown", e.message)
    }
}
UsersController

抛出错误非常简单,直接抛出即可,否则就是返回对象

    @RequestMapping(value = "/users/show")
    fun user(uid: Int): Any {
        val user = userService.show(uid)
        if (user == null){
            throw Exception("没有找到该用户")
        }
        return user
    }

调用 http://127.0.0.1:8080/users/show,如果能够找到该用户就会返回User对象,statusCode = 200

{
    "name":"Wiki",
    "age":18
}

如果调用出错就会返回错误信息,statusCode = 400

{
    "error_code":"not_found",
    "error":"没有找到该用户"
}
总结

上面只是简单的介绍实现的方式,实际上,我们应该根据HTTP status的规范正确响应 statusCode

你可能感兴趣的:(Spring MVC实现REST API 之全局异常统一处理)