在Spring 3 Restful中通过编程的方式更改HTTP响应状态

8 浏览
0 Comments

在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日
0
0 Comments

我得到了一个解决方案,想要与大家分享,也希望听取好的建议。

@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"
}

感谢你们的回复。我仍然需要有关良好实践的指针。

0
0 Comments

你需要改变输出值的类型ResponseEntity。答案在这里:
如何在Spring MVC @ResponseBody方法返回String时回应HTTP 400错误?

0