GatewayExceptionHandler.java 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package com.inspur.smsb.gateway.handler;
  2. import com.alibaba.cola.dto.Response;
  3. import com.alibaba.fastjson.JSON;
  4. import lombok.RequiredArgsConstructor;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
  7. import org.springframework.cloud.gateway.support.NotFoundException;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.core.annotation.Order;
  10. import org.springframework.core.io.buffer.DataBufferFactory;
  11. import org.springframework.http.HttpStatus;
  12. import org.springframework.http.MediaType;
  13. import org.springframework.http.server.reactive.ServerHttpResponse;
  14. import org.springframework.lang.NonNull;
  15. import org.springframework.web.server.ResponseStatusException;
  16. import org.springframework.web.server.ServerWebExchange;
  17. import reactor.core.publisher.Mono;
  18. /**
  19. * 网关统一异常处理
  20. *
  21. * @author liangke
  22. */
  23. @Slf4j
  24. @Configuration
  25. @Order(-1)
  26. @RequiredArgsConstructor
  27. public class GatewayExceptionHandler implements ErrorWebExceptionHandler {
  28. /**
  29. * @param exchange exchange
  30. * @param ex ex
  31. * @return Mono<Void>
  32. */
  33. @NonNull
  34. @Override
  35. public Mono<Void> handle(ServerWebExchange exchange, @NonNull Throwable ex) {
  36. ServerHttpResponse response = exchange.getResponse();
  37. if (exchange.getResponse().isCommitted()) {
  38. return Mono.error(ex);
  39. }
  40. String msg;
  41. if (ex instanceof NotFoundException) {
  42. msg = "服务未找到";
  43. } else if (ex instanceof ResponseStatusException) {
  44. ResponseStatusException responseStatusException = (ResponseStatusException) ex;
  45. msg = responseStatusException.getMessage();
  46. } else {
  47. msg = "内部服务器错误";
  48. }
  49. log.error("[网关异常处理]请求方法:{},请求路径: {},异常信息: {}", exchange.getRequest().getMethod(), exchange.getRequest().getPath(), ex.getMessage());
  50. response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
  51. response.setStatusCode(HttpStatus.OK);
  52. return response.writeWith(Mono.fromSupplier(() -> {
  53. DataBufferFactory bufferFactory = response.bufferFactory();
  54. return bufferFactory.wrap(JSON.toJSONBytes(Response.buildFailure("500", msg)));
  55. }));
  56. }
  57. }