74 lines
2.9 KiB
Kotlin
74 lines
2.9 KiB
Kotlin
package net.halfbinary.scavengerhuntapi.error
|
|
|
|
import net.halfbinary.scavengerhuntapi.error.exception.InvalidEmailException
|
|
import net.halfbinary.scavengerhuntapi.error.exception.LoginFailedException
|
|
import net.halfbinary.scavengerhuntapi.error.exception.NotFoundException
|
|
import net.halfbinary.scavengerhuntapi.error.exception.PreexistingAccountException
|
|
import org.slf4j.LoggerFactory
|
|
import org.springframework.http.HttpStatus
|
|
import org.springframework.http.converter.HttpMessageNotReadableException
|
|
import org.springframework.validation.FieldError
|
|
import org.springframework.web.bind.MethodArgumentNotValidException
|
|
import org.springframework.web.bind.annotation.ExceptionHandler
|
|
import org.springframework.web.bind.annotation.ResponseStatus
|
|
import org.springframework.web.bind.annotation.RestControllerAdvice
|
|
|
|
|
|
@RestControllerAdvice
|
|
class ExceptionHandler {
|
|
companion object {
|
|
private val log = LoggerFactory.getLogger(net.halfbinary.scavengerhuntapi.error.ExceptionHandler::class.java)
|
|
}
|
|
@ExceptionHandler(PreexistingAccountException::class)
|
|
@ResponseStatus(HttpStatus.CONFLICT)
|
|
fun preexistingAccountException(e: PreexistingAccountException): String? {
|
|
return e.message
|
|
}
|
|
|
|
@ExceptionHandler(LoginFailedException::class)
|
|
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
|
fun loginFailedException(e: LoginFailedException): String? {
|
|
return e.message
|
|
}
|
|
|
|
@ExceptionHandler(InvalidEmailException::class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
fun invalidEmailException(e: InvalidEmailException): String? {
|
|
return e.message
|
|
}
|
|
|
|
@ExceptionHandler(NotFoundException::class)
|
|
@ResponseStatus(HttpStatus.NOT_FOUND)
|
|
fun notFoundException(e: NotFoundException): String? {
|
|
return e.message
|
|
}
|
|
|
|
@ExceptionHandler(HttpMessageNotReadableException::class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
fun httpMessageNotReadableException(e: HttpMessageNotReadableException): Map<String, String?> {
|
|
if (e.message?.contains("body is missing")?:false) {
|
|
return simpleMap("body","Body is missing")
|
|
}
|
|
if (e.message?.contains("parameter")?:false) {
|
|
val missingParameter = e.message?.split("parameter ")[1]
|
|
return simpleMap(missingParameter?:"","Missing required parameter $missingParameter")
|
|
}
|
|
log.debug("JSON parsing issue", e)
|
|
return simpleMap("body", "Parsing error")
|
|
}
|
|
|
|
@ExceptionHandler(MethodArgumentNotValidException::class)
|
|
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
|
fun handleValidationExceptions(e: MethodArgumentNotValidException): Map<String, String?> {
|
|
return e.bindingResult.allErrors.associate { error ->
|
|
Pair(
|
|
(error as FieldError).field,
|
|
error.defaultMessage
|
|
)
|
|
}
|
|
}
|
|
|
|
private fun simpleMap(key: String, value: String?): Map<String, String?> {
|
|
return mapOf(Pair(key, value))
|
|
}
|
|
} |