Spring Boot (3.5.0) - Rest 控制器 - 带有 HTML 响应正文的 400

问题描述 投票:0回答:1

我遇到一个问题,当请求 uri 路径变量为空时,Spring Boot Restful 服务返回 400(badRequest) 并带有 html 响应正文,例如: URI 路径:../v1/users/{id}/job 其中 id 为空,因此请求路径将为

../v1/users//job
.

我尝试了以下选项

  1. 在 @ControllerAdvice 类中为“NoHandlerFoundException”添加异常处理程序
  2. 在应用程序配置中添加了 throw-exception-in-no-handler-found
  3. 带有请求映射“/error”的扩展ErrorController
  4. 实现RequestRejectedHandler 没有运气。

如何处理这种异常,在响应中写入自定义json。

示例代码:

import jakarta.validation.constraints.NotNull;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/v1")
@Validated
public class SampleController {@GetMapping(value = 
"/users/{id}/jobs")
public ResponseEntity<?> update(
        @RequestHeader(value = "requestId") String requestId,
        @PathVariable("id") @NotNull String userId) {
    String formattedMessage = "GET jobs [%s 
       %s]".formatted(requestId,userId);
    System.out.print(formattedMessage);
    return ResponseEntity.noContent().build();
   }

}

要求:

curl http://localhost:8080/v1/users//jobs -H 'requestId: b4c0-a6ddc4807cf1'

回应:

HTTP 状态 400 – 错误请求正文 {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px; } h2 {字体大小:16px;} h3 {字体大小:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}

HTTP 状态 400 – 错误请求

html spring-boot rest response http-status-code-400
1个回答
0
投票

异常类处理

您应该有一个名为

BaseResponseError
:

的实体
public class BaseResponseError {
    int error = 0;
    Object message; // <-- Contains your message when err occur

    public static BaseResponseError error(Object message) {
        return new BaseResponseError(1, message);
    }
}

处理异常类:

@RestControllerAdvice // <-- Define the class contains some @ExceptionHandler
public class CustomExceptionHandler {

    @ResponseStatus(HttpStatus.NOT_FOUND) 
    // If this exception  (NohandlerFoundException) occur, 400 will responded.

    @ExceptionHandler(NoHandlerFoundException.class)
    // If the exception is instance of NoHandlerFoundException, Spring will execute this method.

    public BaseResponse handleNoHandlerFoundException(NoHandlerFoundException ex) {
        return BaseResponseError.error(ex.getMessage());
    }
}

您的 Api 将返回如下内容:

{
    "error":1,
    "message":"Hellllllllllo?  What are you doing here"
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.