All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.tairitsu.ignotus.exception.ApiExceptionHandler.kt Maven / Gradle / Ivy

There is a newer version: 1.0.32
Show newest version
package com.tairitsu.ignotus.exception

import com.tairitsu.ignotus.exception.business.UnexpectedException
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 全局异常处理
 */
@ControllerAdvice
open class ApiExceptionHandler {
    private val log: Logger = LoggerFactory.getLogger(this::class.java)

    @Autowired(required = false)
    var reporter: ApiExceptionReporter? = null

    @ExceptionHandler(value = [ApiException::class])
    @ResponseBody
    open fun apiExceptionHandler(
        req: HttpServletRequest,
        response: HttpServletResponse,
        e: ApiException,
    ): Map {
        reporter?.report(e)

        val obj = HashMap()
        obj["errors"] = e.toJSONArray()
        response.status = e.getHttpStatus().value()

        req.setAttribute("api_exception_handler", true)
        return obj
    }

    @ExceptionHandler(value = [Exception::class])
    @ResponseBody
    open fun unexpectedExceptionHandler(
        req: HttpServletRequest,
        response: HttpServletResponse,
        e: Exception,
    ): Map {
        log.error(e.message ?: e.toString(), e)
        val reason = UnexpectedException(e)
        return apiExceptionHandler(req, response, reason)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy