我遇到一个问题,当请求 uri 路径变量为空时,Spring Boot Restful 服务返回 400(badRequest) 并带有 html 响应正文,例如: URI 路径:../v1/users/{id}/job 其中 id 为空,因此请求路径将为
../v1/users//job
.
我尝试了以下选项
如何处理这种异常,在响应中写入自定义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;}
您应该有一个名为
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"
}