我想利用这个代码,以接收与价值观http链接:
@PostMapping(value = "/v1/notification")
public String handleNotifications(@RequestParam("notification") String itemid) {
// parse here the values
return "result successful result";
}
我怎样才能返回HTTP代码200
-成功响应?
也例如,如果有一个异常的代码转换成代码处理我怎么能返回错误404
?
您可以通过注释你的方法去做@ResponseStatus
使用HttpStatus.OK
(但它应该是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<Object> handleMyException(MyException ex, WebRequest req) {
Object resBody = "some message";
return handleExceptionInternal(ex, resBody, new HttpHeaders(), HttpStatus.NOT_FOUND, req);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句