springboot统一异常(kotlin)

在写rest接口时,返回给终端的json格式需要统一,比如下面:

{"errorCode":10000,"info":"","data":{"name":"linxy","age":29}}

其中data部分为自定义内容,根据不同api返回不同内容,errorCode表示返回的错误码,调用者可以根据这个错误码进行相应的判断,info表示错误码的具体描述。

错误码定义,使用枚举方式通常是个好习惯

enum class ErrorCode(val code: Int, val info: String = "") {
    ERROR_OK(10000),
    ERROR_TOKEN(10001, "ERROR TOKEN"),
    ERROR_USER_PASSWORD(10002, "ERROR USER OR PASSWORD")
}

统一返回给api调用者的实体类,内部使用jackson将其转换为json格式

class ResultModel @JvmOverloads constructor(val data: Any? = null) {
    var errorCode: Int? = null
        private set
    var info: String? = null
        private set
    private fun createRespone(rsp : ResultModel) = ResponseEntity(rsp, HttpStatus.OK)
    fun send(err: ErrorCode): ResponseEntity {
        this.errorCode = err.code
        this.info = err.info
        return createRespone(this)
    }
    fun send(code: Int, info: String?) : ResponseEntity {
        this.errorCode = code
        this.info = info
        return createRespone(this)
    }
    fun ok() = send(ErrorCode.ERROR_OK)
}
//自定义api异常返回
public class ApiException(val code: ErrorCode, val data: Any? = null) : Exception(code.info)

@ControllerAdvice
public class GlobExceptionHandle  {

    @ExceptionHandler(ApiException::class)
    fun handleControllerException( ex: ApiException) = ResultModel(ex.data).send(ex.code)

    @ExceptionHandler(NoHandlerFoundException::class)
    fun handleNotFoundException(e: NoHandlerFoundException) : ResponseEntity {
        val status = HttpStatus.NOT_FOUND
        return ResultModel().send(status.value(), e.message)
    }
    @ExceptionHandler(MissingServletRequestParameterException::class)
    fun handleMissingServletRequestParameterException(e: MissingServletRequestParameterException) : ResponseEntity {
        val status = HttpStatus.BAD_REQUEST
        return ResultModel().send(status.value(), e.message)
    }
}

调用例子

@RestController
public class HelloController {

    @RequestMapping("/hello")
    fun sayHello() = "linxy"

    @RequestMapping("/login")
    fun login(@RequestParam name: String, @RequestParam password: String) : ResponseEntity {
        if(name != "linxy" && password != "abc") throw ApiException(ErrorCode.ERROR_USER_PASSWORD)
        return ResultModel(User(name, 29)).ok()
    }

    @RequestMapping("/ok")
    fun ok() : ResponseEntity = ResultModel(User("linxy", 29)).ok()
}

你可能感兴趣的:(springboot统一异常(kotlin))