Skip to content

Instantly share code, notes, and snippets.

@livioribeiro
Created March 1, 2019 14:01
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 livioribeiro/25495600f6685e85019d04777d847825 to your computer and use it in GitHub Desktop.
Save livioribeiro/25495600f6685e85019d04777d847825 to your computer and use it in GitHub Desktop.
Handling controller exceptions on Spring Boot
/*
* Based on: https://docs.spring.io/spring-boot/docs/2.1.3.RELEASE/reference/htmlsingle/#boot-features-error-handling
*/
package com.myorg.myproject.controller.advice
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
import java.time.OffsetDateTime
import javax.servlet.http.HttpServletRequest
abstract class HttpException(val status: HttpStatus, message: String? = null) : Exception(message)
class BadRequestException(message: String? = null) : HttpException(HttpStatus.BAD_REQUEST, message)
class NotFoundException(message: String? = null) : HttpException(HttpStatus.NOT_FOUND, message)
class ErrorResponse(
val status: Int,
val message: String
) {
val timestamp: OffsetDateTime = OffsetDateTime.now()
}
@RestControllerAdvice(basePackages = ["com.myorg.myproject.controller"])
class ErrorHandlerControllerAdvice : ResponseEntityExceptionHandler() {
@ExceptionHandler(HttpException::class)
fun handleNotFoundException(request: HttpServletRequest, ex: HttpException): ErrorResponse {
val status = ex.status
return ErrorResponse(status.value(), ex.message ?: status.reasonPhrase)
}
@ExceptionHandler(Exception::class)
fun handleException(request: HttpServletRequest, ex: Exception): ErrorResponse {
val status = getStatus(request)
return ErrorResponse(status.value(), ex.message ?: status.reasonPhrase)
}
private fun getStatus(request: HttpServletRequest): HttpStatus {
val statusCode = request.getAttribute("javax.servlet.error.status_code") as Int?
?: return HttpStatus.INTERNAL_SERVER_ERROR
return HttpStatus.valueOf(statusCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment