在Spring 3 Restful中通过编程的方式更改HTTP响应状态
在Spring 3 Restful中通过编程的方式更改HTTP响应状态
我有一个如下的控制器
@Controller("myController") @RequestMapping("api") public class MyController { @RequestMapping(method = RequestMethod.GET, value = "/get/info/{id}", headers = "Accept=application/json") public @ResponseBody Student getInfo(@PathVariable String info) { ................. } @ExceptionHandler(Throwable.class) @ResponseStatus( HttpStatus.EXPECTATION_FAILED) @ResponseBody public String handleIOException(Throwable ex) { ErrorResponse errorResponse = errorHandler.handelErrorResponse(ex); return errorResponse.toString(); } }
该控制器具有错误处理机制,在错误处理选项中,它总是返回期望失败状态代码417。但我需要根据错误类型设置动态错误Http状态码,例如500、403等。我该怎么做?
admin 更改状态以发布 2023年5月23日
我得到了一个解决方案,想要与大家分享,也希望听取好的建议。
@Controller("myController") @RequestMapping("api") public class MyController { @RequestMapping(method = RequestMethod.GET, value = "/get/info/{id}", headers = "Accept=application/json") public @ResponseBody Student getInfo(@PathVariable String info) { // ... } } // ... @ExceptionHandler(Throwable.class) //@ResponseStatus( HttpStatus.EXPECTATION_FAILED)<
在REST客户端中,期望输出:
502 Bad Gateway { "status":"BAD_GATEWAY", "error":"java.lang.UnsupportedOperationException", "message":"Some error message" }
感谢你们的回复。我仍然需要有关良好实践的指针。