diff --git a/src/main/java/cokr/xit/applib/HttpStatusCodeException.java b/src/main/java/cokr/xit/applib/HttpStatusCodeException.java new file mode 100644 index 0000000..263a6f4 --- /dev/null +++ b/src/main/java/cokr/xit/applib/HttpStatusCodeException.java @@ -0,0 +1,17 @@ +package cokr.xit.applib; + +public class HttpStatusCodeException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + private int status; + + public int getStatus() { + return this.status; + } + + public HttpStatusCodeException(int statusCode, String message){ + super(message); + this.status = statusCode; + } +} diff --git a/src/main/java/cokr/xit/applib/HttpStatusCodeExceptionControllerAdvice.java b/src/main/java/cokr/xit/applib/HttpStatusCodeExceptionControllerAdvice.java new file mode 100644 index 0000000..004e0e9 --- /dev/null +++ b/src/main/java/cokr/xit/applib/HttpStatusCodeExceptionControllerAdvice.java @@ -0,0 +1,27 @@ +package cokr.xit.applib; + +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +@ControllerAdvice +public class HttpStatusCodeExceptionControllerAdvice extends ResponseEntityExceptionHandler { + + @ExceptionHandler(HttpStatusCodeException.class) + public ResponseEntity handleHttpStatusCodeException( + final HttpStatusCodeException exception, final WebRequest webRequest) { + int status = exception.getStatus(); + String body = exception.getMessage(); + HttpHeaders header = new HttpHeaders(); + header.setContentType(new MediaType(MediaType.TEXT_PLAIN, StandardCharsets.UTF_8)); + return handleExceptionInternal(exception, body, header, HttpStatus.valueOf(status), webRequest); + } + +}