Hideout/templates/exceptions.mustache

30 lines
1.2 KiB
Plaintext
Raw Normal View History

2023-10-08 06:06:06 +00:00
package {{apiPackage}}
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import {{javaxPackage}}.servlet.http.HttpServletResponse
import {{javaxPackage}}.validation.ConstraintViolationException
// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception
sealed class ApiException(msg: String, val code: Int) : Exception(msg)
class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code)
@ControllerAdvice
class DefaultExceptionHandler {
@ExceptionHandler(value = [ApiException::class])
fun onApiException(ex: ApiException, response: HttpServletResponse): Unit =
response.sendError(ex.code, ex.message)
@ExceptionHandler(value = [NotImplementedError::class])
fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit =
response.sendError(HttpStatus.NOT_IMPLEMENTED.value())
@ExceptionHandler(value = [ConstraintViolationException::class])
fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit =
response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message })
}