【问题标题】:How to validated rest url in spring boot?如何在spring boot中验证rest url?
【发布时间】:2018-07-19 10:28:38
【问题描述】:

在 Spring Boot 中验证 Rest URL。 要求:如果我点击了错误的 URL,那么它应该抛出一个自定义异常。 前任。正确的 URL 是 "/fulfillment/600747l/send_to_hub" 如果我​​点击 "/api/600747l/send_to_hub_1" 那么它应该返回异常 “404:- 未找到 URL。”。

现在它返回 "500 : -

 {
  "timestamp": 1531995246549,
  "status": 500,
  "error": "Internal Server Error",
  "message": "Invalid Request URL.",
  "path": "/api/600747l/send_to_hub_1"
}"

【问题讨论】:

  • 我猜你想要自定义 404 处理程序,

标签: spring spring-mvc spring-boot spring-data spring-boot-actuator


【解决方案1】:

你需要用注解@ControllerAdvice 编写NewClass,它将所有异常重定向到这个NewClass。 例子

您的自定义异常类:

@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class IOApiException extends IOException {
    private ErrorReason errorReason;
    public IOApiException(String message, ErrorReason errorReason) {
        super(message);
        this.errorReason = errorReason;
    }
}

现在是 CustomExceptionHandler 类 -

@ControllerAdvice
@RestController
public class GlobalExceptionHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());


    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = IOApiException.class)
    public GlobalErrorResponse handleException(IOApiException e) {
        logger.error("UNAUTHORIZED: ", e);
        return new GlobalErrorResponse("URL Not Found", HttpStatus.UNAUTHORIZED.value(), e.getErrorReason());
    }


 //this to handle customErrorResponseClasses
public GlobalErrorResponse getErrorResponseFromGenericException(Exception ex) {
    if (ex == null) {
        return handleException(new Exception("INTERNAL_SERVER_ERROR"));
    } 
     else if (ex instanceof IOApiException) {
        return handleException((IOApiException) ex);
    }
}

现在你的错误响应类:

public class GlobalErrorResponse {
    private String message;
    @JsonIgnore
    private int statusCode;
    private ErrorReason reason;
}

ErrorReason 类

public enum ErrorReason {
    INTERNAL_SERVER_ERROR,
    INVALID_REQUEST_PARAMETER,
    INVALID_URL
}

添加并注册一个在这种异常情况下调用 GlobalExceptionHandler 的过滤器

  public class ExceptionHandlerFilter implements Filter {
    private final GlobalExceptionHandler globalExceptionHandler;
    public ExceptionHandlerFilter(GlobalExceptionHandler globalExceptionHandler) {
        this.globalExceptionHandler = globalExceptionHandler;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            chain.doFilter(request, response);
        } catch (Exception exception) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            GlobalErrorResponse errorResponse = globalExceptionHandler.getErrorResponseFromGenericException(exception);
            httpResponse.setStatus(errorResponse.getStatusCode());
            response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse));
        }
    }

    @Override
    public void destroy() {

    }
}

像这样,您可以添加任意数量的异常......并且可以手动处理它。

【讨论】:

    【解决方案2】:

    根据您的问题,首先您需要定义一个基本 url(例如-/api),以便必须通过您的控制器处理任何 url。现在在基本 url 之后,如图所示 /api/600747l/send_to_hub_1 @PathVariable int id。这种情况很重要,因为 Spring 文档说如果使用 @PathVariable 注释的方法参数不能转换为指定类型(在我们的例子中为 int),它将被暴露为 String。因此,它可能会导致 TypeMismatchException。

    为了处理这个问题,我将在@Controller 级别使用@ExceptionHandler 注释。这种方法不适合这种情况。我只需要在 Controller 中进行 2 处更改:

    1.添加MessageSource字段 2.添加异常处理方法

     @Autowired
        private MessageSource messageSource;
    ...
        @ExceptionHandler(TypeMismatchException.class)
        @ResponseStatus(value=HttpStatus.NOT_FOUND)
        @ResponseBody
        public ErrorInfo handleTypeMismatchException(HttpServletRequest req, TypeMismatchException ex) {
            Locale locale = LocaleContextHolder.getLocale();
            String errorMessage = messageSource.getMessage("error.bad.smartphone.id", null, locale);
    
            errorMessage += ex.getValue();
            String errorURL = req.getRequestURL().toString();
    
            return new ErrorInfo(errorURL, errorMessage);
        }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-23
      • 1970-01-01
      • 2022-01-10
      • 2016-12-01
      • 2017-06-28
      • 2022-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多