JsonErrorWebExceptionHandler.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.fdkankan.gateway.exception;
  2. import com.fdkankan.common.constant.ServerCode;
  3. import com.fdkankan.common.exception.BusinessException;
  4. import org.springframework.boot.autoconfigure.web.ErrorProperties;
  5. import org.springframework.boot.autoconfigure.web.ResourceProperties;
  6. import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
  7. import org.springframework.boot.web.error.ErrorAttributeOptions;
  8. import org.springframework.boot.web.reactive.error.ErrorAttributes;
  9. import org.springframework.context.ApplicationContext;
  10. import org.springframework.http.HttpStatus;
  11. import org.springframework.web.reactive.function.server.*;
  12. import java.util.Calendar;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. public class JsonErrorWebExceptionHandler extends DefaultErrorWebExceptionHandler {
  16. public JsonErrorWebExceptionHandler(ErrorAttributes errorAttributes,
  17. ResourceProperties resourceProperties,
  18. ErrorProperties errorProperties,
  19. ApplicationContext applicationContext) {
  20. super(errorAttributes, resourceProperties, errorProperties, applicationContext);
  21. }
  22. @Override
  23. protected Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) {
  24. // 这里其实可以根据异常类型进行定制化逻辑
  25. Throwable error = super.getError(request);
  26. Map<String, Object> errorAttributes = new HashMap<>(8);
  27. if(error instanceof BusinessException){
  28. errorAttributes.put("code", ((BusinessException) error).getCode());
  29. errorAttributes.put("message", ((BusinessException) error).getMessage());
  30. }else{
  31. errorAttributes.put("code", ServerCode.SYSTEM_ERROR.code());
  32. errorAttributes.put("message", ServerCode.SYSTEM_ERROR.message());
  33. }
  34. errorAttributes.put("method", request.methodName());
  35. errorAttributes.put("path", request.path());
  36. errorAttributes.put("timestamp", Calendar.getInstance().getTimeInMillis());
  37. return errorAttributes;
  38. }
  39. @Override
  40. protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
  41. return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
  42. }
  43. @Override
  44. protected int getHttpStatus(Map<String, Object> errorAttributes) {
  45. // 这里其实可以根据errorAttributes里面的属性定制HTTP响应码
  46. return HttpStatus.INTERNAL_SERVER_ERROR.value();
  47. }
  48. }