Skip to content

Instantly share code, notes, and snippets.

@brunapereira
Last active May 11, 2020 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunapereira/37c4283b9980ae378f5eb3a70704a8d4 to your computer and use it in GitHub Desktop.
Save brunapereira/37c4283b9980ae378f5eb3a70704a8d4 to your computer and use it in GitHub Desktop.
Example of a Spring ControllerAdvice
@RestControllerAdvice
class ExceptionHandler {
@ResponseStatus(INTERNAL_SERVER_ERROR) [1]
@ExceptionHandler(Exception::class)
fun onException(exception: Exception): ApiError {
log.error("error=general message=${exception.message}", exception)
return ApiError("INTERNAL_SERVER_ERROR", exception.message ?: "")
}
@ResponseStatus(NOT_ACCEPTABLE) [2]
@ExceptionHandler(ApiVersionNotAcceptableException::class)
fun onApiVersionNotAcceptableException(exception: ApiVersionNotAcceptableException): ApiError {
log.error("error=api version message=${exception.message}", exception)
return ApiError("VERSION_NOT_ACCEPTABLE", exception.message ?: "")
}
@ResponseStatus(BAD_REQUEST) [3]
@ExceptionHandler(MethodArgumentNotValidException::class)
fun onMethodArgumentNotValidException(exception: MethodArgumentNotValidException): ApiError {
log.error("error=validation message=${exception.message}", exception)
val errors: Map<String, String> = exception
.bindingResult
.allErrors
.associateBy({ (it as FieldError).field }, { it.defaultMessage ?: "" })
return ApiError("REQUEST_VALIDATION_ERROR", "Some fields are invalid", errors)
}
}
data class ApiError(
val code: String,
val message: String,
val details: Map<String, String>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment