springboot 3.2.1
@Getter
public abstract class OutsourcingException extends RuntimeException {
private final Map<String, String> validation = new HashMap<>();
public OutsourcingException(String message) {
super(message);
}
public abstract int getStatusCode();
public void addValidation(String filedName, String message) {
validation.put(filedName, message);
}
}
@Getter
public class ErrorResponse {
private final String code;
private final String message;
private final Map<String, String> validation;
@Builder
public ErrorResponse(String code, String message, Map<String, String> validation) {
this.code = code;
this.message = message;
this.validation = (validation != null) ? validation : new HashMap<>();
}
public void addValidation(String fieldName, String errorMessage) {
this.validation.put(fieldName, errorMessage);
}
}
@RestControllerAdvice
public class ExceptionController {
@ExceptionHandler(OutsourcingException.class)
public ResponseEntity<ErrorResponse> outsourcingException(OutsourcingException e) {
int statusCode = e.getStatusCode();
ErrorResponse body = ErrorResponse.builder()
.code(String.valueOf(statusCode))
.message(e.getMessage())
.validation(e.getValidation())
.build();
return ResponseEntity.status(statusCode)
.body(body);
}
}