diff --git a/src/main/java/ext/Ext.kt b/src/main/java/ext/Ext.kt index 626ec167..b33ae136 100644 --- a/src/main/java/ext/Ext.kt +++ b/src/main/java/ext/Ext.kt @@ -1,5 +1,6 @@ package ext +import icu.samnyan.aqua.net.utils.ApiException import io.ktor.client.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.contentnegotiation.* @@ -19,8 +20,8 @@ typealias Str = String typealias Bool = Boolean // Make it easier to throw a ResponseStatusException -operator fun HttpStatus.invoke(message: String? = null): Nothing = throw ResponseStatusException(this, message ?: this.reasonPhrase) -operator fun Int.compareTo(message: String): Int = throw ResponseStatusException(HttpStatus.valueOf(this), message) +operator fun HttpStatus.invoke(message: String? = null): Nothing = throw ApiException(value(), message ?: this.reasonPhrase) +operator fun Int.compareTo(message: String): Int = throw ApiException(this, message) // Email validation // https://www.baeldung.com/java-email-validation-regex diff --git a/src/main/java/icu/samnyan/aqua/net/utils/ErrorResponse.kt b/src/main/java/icu/samnyan/aqua/net/utils/ErrorResponse.kt new file mode 100644 index 00000000..12a1032a --- /dev/null +++ b/src/main/java/icu/samnyan/aqua/net/utils/ErrorResponse.kt @@ -0,0 +1,17 @@ +package icu.samnyan.aqua.net.utils + +import ext.Str +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler + +class ApiException(val code: Int, message: Str) : RuntimeException(message) + +@ControllerAdvice +class GlobalExceptionHandler { + @ExceptionHandler(ApiException::class) + fun handleCustomApiException(e: ApiException): ResponseEntity { + // On error, return the error code and message + return ResponseEntity.status(e.code).body(e.message) + } +} \ No newline at end of file