Created
October 11, 2019 22:42
-
-
Save akhilbojedla/4903d99ab00d1f4c689eb7b9acccc22e to your computer and use it in GitHub Desktop.
GlobalErrorHandler to handle errors globally in Spring WebFlux
This file contains hidden or 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
package com.bytecodehq; | |
import reactor.core.publisher.Mono; | |
import com.fasterxml.jackson.core.JsonProcessingException; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import java.io.IOException; | |
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.annotation.Order; | |
import org.springframework.core.io.buffer.DataBuffer; | |
import org.springframework.core.io.buffer.DataBufferFactory; | |
import org.springframework.http.HttpStatus; | |
import org.springframework.http.MediaType; | |
import org.springframework.web.server.ServerWebExchange; | |
@Configuration | |
@Order(-2) | |
public class GlobalErrorHandler implements ErrorWebExceptionHandler { | |
private ObjectMapper objectMapper; | |
public GlobalErrorHandler(ObjectMapper objectMapper) { | |
this.objectMapper = objectMapper; | |
} | |
@Override | |
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) { | |
DataBufferFactory bufferFactory = serverWebExchange.getResponse().bufferFactory(); | |
if (throwable instanceof IOException) { | |
serverWebExchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST); | |
DataBuffer dataBuffer = null; | |
try { | |
dataBuffer = bufferFactory.wrap(objectMapper.writeValueAsBytes(new HttpError("Custom message"))); | |
} catch (JsonProcessingException e) { | |
dataBuffer = bufferFactory.wrap("".getBytes()); | |
} | |
serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON); | |
return serverWebExchange.getResponse().writeWith(Mono.just(dataBuffer)); | |
} | |
serverWebExchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR); | |
serverWebExchange.getResponse().getHeaders().setContentType(MediaType.TEXT_PLAIN); | |
DataBuffer dataBuffer = bufferFactory.wrap("Unknown error".getBytes()); | |
return serverWebExchange.getResponse().writeWith(Mono.just(dataBuffer)); | |
} | |
public class HttpError { | |
private String message; | |
HttpError(String message) { | |
this.message = message; | |
} | |
public String getMessage() { | |
return message; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment