Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 缺少Swagger required参数时返回500,而不是404_Java_Spring Boot_Rest_Swagger - Fatal编程技术网

Java 缺少Swagger required参数时返回500,而不是404

Java 缺少Swagger required参数时返回500,而不是404,java,spring-boot,rest,swagger,Java,Spring Boot,Rest,Swagger,我有一个REST端点,它有一个请求参数“myParam”。这是一个必需的参数,如果没有该参数,对该端点发出的任何GET请求都将被视为错误请求。我使用Swagger强调这个参数是必需的,如下所示 @ApiParam(required = true) @RequestParam(value = "myParam") String myParam 问题是,当我通过邮递员向该端点提交GET时,返回的HTTP错误是一个500,表示未提供所需的参数myParam。有没有办法重构它,以便如果Swagger标

我有一个REST端点,它有一个请求参数“myParam”。这是一个必需的参数,如果没有该参数,对该端点发出的任何GET请求都将被视为错误请求。我使用Swagger强调这个参数是必需的,如下所示

@ApiParam(required = true) @RequestParam(value = "myParam") String myParam

问题是,当我通过邮递员向该端点提交GET时,返回的HTTP错误是一个500,表示未提供所需的参数myParam。有没有办法重构它,以便如果Swagger标记为required的参数丢失,则响应为404?

解决方案可能是创建一个类,并用
@ControllerAdvice
对其进行注释。此类的方法负责处理作为参数传递的特定异常。在
500
错误中,应该有一个异常堆栈跟踪,如“由..org.somepackage.SomeException…”

1) 您可以创建包含消息和HttpStatus代码的自定义类:

public class ExceptionResponse {
  private HttpStatus httpStatus;
  private String errorMessage;
  //getters;setters;
}
2)
@ControllerAdvice
注释类应如下所示:

@ControllerAdvice
public class RestExceptionHandler {

@ExceptionHandler(value = SomeException.class)
public ResponseEntity<ExceptionResponse> handleMissingRequiredParameters(SomeException ex) {
    ExceptionResponse exceptionResponse = new ExceptionResponse();
    exceptionResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
    exceptionResponse.setErrorMessage(ex.getMessage());
    return new ResponseEntity<>(exceptionResponse, exceptionResponse.getHttpStatus());
}
}
@ControllerAdvice
公共类RestExceptionHandler{
@ExceptionHandler(值=SomeException.class)
public ResponseEntity handleMissingRequiredParameters(某些异常,例如){
ExceptionResponse ExceptionResponse=新的ExceptionResponse();
exceptionResponse.setHttpStatus(HttpStatus.BAD_请求);
setErrorMessage(例如getMessage());
返回新的ResponseEntity(exceptionResponse,exceptionResponse.getHttpStatus());
}
}

现在,当抛出
SomeException
时,您将看到的实际响应是带有自定义
httpStatus
errorMessage

ExceptionResponse
JSON,您能用发送的GET请求更新问题吗?非常感谢,我会尝试一下