我想使用此代码接收带有值的http链接:
@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
// parse here the values
return "result successful result";
}
如何返回http代码200 – 成功响应?
而且,例如,如果代码处理中存在代码异常,我该如何返回错误404?
解决方法:
您可以使用HttpStatus.OK使用@ResponseStatus注释您的方法来执行此操作(但默认情况下应为200),如下所示:
一些控制器
@PostMapping(value = "/v1/notification")
@ResponseStatus(HttpStatus.OK)
public String handleNotifications(@RequestParam("notification") String itemid) throws MyException {
if(someCondition) {
throw new MyException("some message");
}
// parse here the values
return "result successful result";
}
现在,为了在处理特定异常时返回自定义代码,您可以创建一个完整的单独控制器来执行此操作(您可以在同一控制器中执行此操作),该控制器从ResponseEntityExceptionHandler开始并使用@RestControllerAdvice进行注释,并且必须具有处理该特定异常的方法如下所示:
异常处理控制器
@RestControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyException.class)
protected ResponseEntity handleMyException(MyException ex, WebRequest req) {
Object resBody = "some message";
return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
}
}
标签:java,spring,spring-boot-2
来源: https://codeday.me/bug/20190717/1486171.html