异常的Http状态代码

异常的Http状态代码

本文介绍了异常的Http状态代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SpringBoot控制器,并且我想为Exceptions返回正确的http代码状态.因此,我的问题是:哪一个http状态代码更适合Exception,那么"500"或"409"是什么?

i have a SpringBoot controller, and i want to return the correct http code status for Exceptions. So, my question is: Which http statu code is better for Exception the "500" one or "409" one?

这是我的代码:

@PostMapping(value = {"", "/"})
public ResponseEntity<Response> create(@RequestBody StudioDto studioDto,
        ServletRequest servletRequest, ServletResponse servletResponse) {

    Response response = new Response();

    try {
        studioService.createStudio(studioDto);
        response.setMessage("The studio was create");
        response.setStatusCode(HttpServletResponse.SC_CREATED);

    } catch (Exception e) {
        response.setMessage("Op we have a little problem");
        response.setErrorMessage(e.getMessage());

        //Which one
        //this one 5xx
        response.setStatusCode(500);
        //Or this one 4xx
        response.setStatusCode(409);
    }

    return new ResponseEntity(response, response.getHttpStatus());
}

推荐答案

这不是处理异常的推荐方法,您应该使用控制器建议,选中此链接

This is not the recommended way to handle exceptions, you should use controller advice , check this link

状态代码是由特定情况定义的,500表示内部服务器错误,我将使用它来解决未指定原因的问题,因为409它会重新标记目标资源上的冲突

The status code is defined by the specific scenario , 500 means internal server error which I would use for a problem which it's cause is not specified, for 409 it resembels conflict on the target resource

您还有许多其他适合不同情况的状态代码,所以我想说没有特定的状态代码是正确的答案,您可以检查此链接以获取更多信息

you have many other status code which is suitable in different cases so I would say no specific status code is the right answer, you can check this link for more info

这篇关于异常的Http状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:55