Skip to content

Instantly share code, notes, and snippets.

@susimsek
Created December 25, 2020 16:09
Show Gist options
  • Save susimsek/a3130d2ae7f70b9e629f3ba1e65004f7 to your computer and use it in GitHub Desktop.
Save susimsek/a3130d2ae7f70b9e629f3ba1e65004f7 to your computer and use it in GitHub Desktop.
Spring Boot General Response Status Exceptions
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class AppException extends RuntimeException {
public AppException(String message) {
super(message);
}
public AppException(String message, Throwable cause) {
super(message, cause);
}
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
public BadRequestException(String message, Throwable cause) {
super(message, cause);
}
}
@ResponseStatus(HttpStatus.CONFLICT)
public class ConflictException extends RuntimeException {
public ConflictException(String message) {
super(message);
}
public ConflictException(String message, Throwable cause) {
super(message, cause);
}
}
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private String resourceName;
private String fieldName;
private Object fieldValue;
public ResourceNotFoundException( String resourceName, String fieldName, Object fieldValue) {
super(String.format("%s not found with %s : '%s'", resourceName, fieldName, fieldValue));
this.resourceName = resourceName;
this.fieldName = fieldName;
this.fieldValue = fieldValue;
}
public String getResourceName() {
return resourceName;
}
public String getFieldName() {
return fieldName;
}
public Object getFieldValue() {
return fieldValue;
}
}
@RestController
@Hidden
@FieldDefaults(level = AccessLevel.PRIVATE,makeFinal=true)
@RequestMapping("/versions/1/tests")
public class TestController {
@PostMapping("/test")
@ResponseStatus(HttpStatus.OK)
public void test() {
throw new ConflictException("You have already exists this invoice");
throw new ResourceNotFoundException("Invoice", "id", id);
throw new BadRequestException("This invoice does not contain tax number");
throw new AppException("This invoice does not upload");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment