【问题标题】:Uncaught Exception : class org.springframework.web.HttpRequestMethodNotSupportedException : Request method 'PUT' not supported未捕获的异常:类 org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法“PUT”
【发布时间】:2018-09-11 14:03:42
【问题描述】:

我在 Spring Boot 中创建了 PatchMapping 当我想修改并使用方法 Put it

====== 错误:未捕获的异常:类 org.springframework.web.HttpRequestMethodNotSupportedException: 不支持请求方法“PUT”===================

如果我使用方法patch它工作正常。

【问题讨论】:

  • 显示你正在使用的实际代码
  • 在 restcontroller 我有 Patchmapping ,没有 putMapping 所以当我从客户端使用 put 时出现错误 500“内部服务器错误”。所以我想返回用户错误 400“put 方法没有。”
  • 相信我们理解您的问题,但我们只有看到您的代码才能修复您的代码,否则只是一场疯狂的猜谜游戏。

标签: spring-boot


【解决方案1】:

如果你想通过PUT动词调用服务,你需要添加spring-boot注解:

    @RequestMapping(path = "/yourURL", method = RequestMethod.PUT)

PATCH 与 PUT 不同。您可以找到更多信息:

What is the difference between PUT, POST and PATCH?

【讨论】:

  • 异常告诉我们Request method 'PUT' not supported。与POSTPATCH 无关。
  • 好的。如果需要进行更新,则需要将服务声明为 method=RequestMethod.PUT,而不是 POST。在包含要更新的值的输入参数上也需要注释 @RequestBody。
  • 谢谢,但是当我使用补丁正常工作但我想在使用方法时处理 put ,现在错误 { "status": 500, "message": "internal server error" }
  • 我想处理它并返回 400 。 spring 如何在restcontroller中捕获异常方法
  • 你需要一个实现ErrorController的类。 @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity processValidationError(MethodArgumentNotValidException ex) { RestInvalidParameter error = new RestInvalidParameter(ex); LOGGER.log(Level.WARNING, "错误: {0}", 错误); return new ResponseEntity(error, HttpStatus.BAD_REQUEST); }
【解决方案2】:

如果要捕获异常,请创建一个实现 ErrorController 的类:

@Controller
@ControllerAdvice
public class RestErrorHandler implements ErrorController {

@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseEntity<RestInvalidParameter> processValidationError(MethodArgumentNotValidException ex) {
        return new ResponseEntity<>(ex, HttpStatus.BAD_REQUEST);
    }
}

【讨论】:

  • @Nacho 对于RestErrorHandler类不需要实现ErrorController
  • @ExceptionHandler(Exception.class) public void methodNotAllowed(Exception ex) throws ResourceNotFoundException, URISyntaxException, ResourceViolationException,ResourceNotFoundException ,ResourceNotFoundException{ throw ex; }
  • 请解决 ResourceNotFoundException, URISyntaxException, ResourceViolationException,ResourceNotFoundException ,ResourceNotFoundException 是从异常扩展的类,但我不知道使用异常时哪个类有错误。
  • @Nacho 有什么建议
  • 您可以将集合设置为注解@ExceptionHandler({ResourceNotFoundException.class, URISyntaxException.class, ResourceViolationException.class},例如,在方法内部,使用“instanceof”来抛出不同的HttpStatus每个例外。
猜你喜欢
  • 2020-10-29
  • 2021-09-20
  • 2020-05-19
  • 2015-06-26
  • 2022-01-06
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2014-05-15
相关资源
最近更新 更多