Skip to content

Instantly share code, notes, and snippets.

@anny0739
Last active December 21, 2020 13:06
Show Gist options
  • Save anny0739/c9d0b5389e176c80b72d1762380236f3 to your computer and use it in GitHub Desktop.
Save anny0739/c9d0b5389e176c80b72d1762380236f3 to your computer and use it in GitHub Desktop.
@Component
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
ErrorAttribute errorAttribute = this.buildResponse(throwable);
serverWebExchange.getResponse().setStatusCode(errorAttribute.getStatus());
serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
DataBufferFactory bufferFactory = serverWebExchange.getResponse().bufferFactory();
DataBuffer dataBuffer = bufferFactory
.wrap(errorAttribute.getErrorMessageBytes());
return serverWebExchange.getResponse().writeWith(Mono.just(dataBuffer));
}
private ErrorAttribute buildResponse(Throwable throwable) {
if (throwable instanceof GatewayException) {
GatewayException ex = (GatewayException) throwable;
ErrorCode errorCode = ex.getErrorCode();
return new ErrorAttribute(errorCode.getHttpStatus(), JsonUtils
.convertBytes(new Errors<>(errorCode.getCode(), ex.getMessage())));
}
ErrorCode errorCode = ErrorCode.SERVER_EXCEPTION;
return new ErrorAttribute(errorCode.getHttpStatus(), JsonUtils
.convertBytes(new Errors<>(errorCode.getCode(), throwable.getMessage())));
}
@AllArgsConstructor
@Getter
public static class ErrorAttribute {
private final HttpStatus status;
private final byte[] errorMessageBytes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment