Last active
December 21, 2020 13:06
-
-
Save anny0739/c9d0b5389e176c80b72d1762380236f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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