Last active
May 11, 2020 02:59
-
-
Save brunapereira/37c4283b9980ae378f5eb3a70704a8d4 to your computer and use it in GitHub Desktop.
Example of a Spring ControllerAdvice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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