代码之家  ›  专栏  ›  技术社区  ›  Alexei

返回“错误请求”,但需要“未找到”

  •  1
  • Alexei  · 技术社区  · 4 年前

    这里是我的自定义处理程序异常:

    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ResponseStatus;
    
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public class ProductNotFoundException extends RuntimeException
    {
        public ProductNotFoundException(String exception) {
            super(exception);
        }
    }
    

    所以什么时候扔 ProductNotFoundException 则响应状态必须为 404 . 因为我添加了注释:

    @ResponseStatus(HttpStatus.NOT_FOUND)
    

    此处为控制器:

     import com.google.gson.JsonParseException;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    @PutMapping("/product")
        public ResponseEntity<Product> updateProduct(@RequestBody String payload) {
            Product product = getProduct(payload);
            Optional<Product> findProduct = productRepository.findById(product.getId());
            if (findProduct.isPresent()) {
                return new ResponseEntity<Product>(updateProduct, HttpStatus.OK);
            } else {
                String error = "Not found product with id = " + product.getId();
                throw new ProductNotFoundException(error);
            }
        }
    

    ProductNotFoundException异常

    但当我发送put请求时,产品id不存在,http响应:

    {
      "message": "Not found product with id = 123"
    }
    // PUT http://127.0.0.1:9090/api/v1/product
    // HTTP/1.1 400 
    // Content-Type: application/json
    // Transfer-Encoding: chunked
    // Date: Wed, 09 Sep 2020 16:21:22 GMT
    // Connection: close
    // Request duration: 0.138291s
    

    问题是:为什么http状态是 ? 404

    0 回复  |  直到 4 年前
        1
  •  2
  •   Nakul Goyal    4 年前

    @RestControllerAdvice
    public class WebRestControllerAdvice {
      
      @ExceptionHandler(CustomNotFoundException.class)
      @ResponseStatus(HttpStatus.NOT_FOUND)
      public ResponseMsg handleNotFoundException(Throwable ex) {
        ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
        return responseMsg;
      }
    }
    
        2
  •  0
  •   want2learn    4 年前

    Http状态400表示这是一个错误的请求。我不知道你用什么来测试这个, Swagger postman

    尝试删除你的 content-type

        3
  •  0
  •   Dharman Aman Gojariya    4 年前

    将返回的类型参数更改为泛型通配符( <?> )允许您使用以下代码来返回您喜欢的任何状态,而不是在将有意义的错误消息作为字符串包含时引发异常—您当前需要 照你所说的做,你将永远返回一个 Product 车身类型。

    else {
        String error = "Not found product with id = " + product.getId();
        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(error);
    }
    

    updateProduct )它将在标题中返回。我在这里假设你宁愿把尸体定为 引用已确定的当前值 Optional 参数。这可以通过以下方法实现:

    return new ResponseEntity.ok(findProduct.get());