Skip to content

Instantly share code, notes, and snippets.

@kapresoft
Last active May 12, 2023 01:12
Show Gist options
  • Save kapresoft/92b9c9ad01b503cf647ce7855460084a to your computer and use it in GitHub Desktop.
Save kapresoft/92b9c9ad01b503cf647ce7855460084a to your computer and use it in GitHub Desktop.
package com.kapresoft.api;
import com.kapresoft.api.exception.client.BadRequestException;
import com.kapresoft.api.exception.client.NotFoundException;
import org.springframework.http.ProblemDetail;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.util.DefaultUriBuilderFactory;
import java.net.URI;
import java.util.Map;
@ControllerAdvice
public class APIExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<HttpClientErrorException> handleNotFound(NotFoundException ex, WebRequest req) {
ProblemDetail p = ProblemDetail.forStatus(ex.getStatusCode());
URI type = new DefaultUriBuilderFactory()
.uriString("https://yoursite.acme.com/not-found/{error-code}")
.build(Map.of("error-code", ex.getErrorCode()));
p.setDetail(ex.getStatusText());
p.setTitle("Object not found");
p.setType(type);
p.setProperty("hint", "hint-value");
return ResponseEntity.of(p).build();
}
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<HttpClientErrorException> handleBadRequest(BadRequestException ex, WebRequest req) {
ProblemDetail p = ProblemDetail.forStatus(ex.getStatusCode());
URI type = new DefaultUriBuilderFactory()
.uriString("https://yoursite.acme.com/bad-request/{error-code}")
.build(Map.of("error-code", ex.getErrorCode()));
p.setDetail(ex.getStatusText());
p.setTitle("Bad Request");
p.setType(type);
p.setProperty("hint", "hint-value");
return ResponseEntity.of(p).build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment