使用Try Catch时,并非所有代码路径都返回值 [英] Not all code paths return value while using Try Catch

查看:147
本文介绍了使用Try Catch时,并非所有代码路径都返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我得到了并非所有代码路径都返回值".我有下面的代码.我想我会适当返回,但仍然有错误.

I have been getting "not all code paths return value" in the following code. I have the code below. I think I am returning appropriately but still there is an error.

[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
    try
    {
        Employee incomingEmployee = employee;
        if (incomingEmployee == null)
        {
        Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
        }
        else if (UserManager.AddUser(employee) > 0)
        {
        return Request.CreateResponse(HttpStatusCode.Created);
        }
        else
        {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
        }
    }
    catch (Exception ex)
    {
       return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

推荐答案

您在第一个if语句中忘记了return语句.

You forgot a return statement in the first if statement.

[Route("User")]
public HttpResponseMessage Post([FromBody] Employee employee)
//FromBody forces the web api to read a simple tye from the request body.
{
    try
    {
        Employee incomingEmployee = employee;
        if (incomingEmployee == null)
        {
     -->return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read the request");
        }
        else if (UserManager.AddUser(employee) > 0)
        {
        return Request.CreateResponse(HttpStatusCode.Created);
        }
        else
        {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to database");
        }
    }
    catch (Exception ex)
    {
       return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
    }
}

这篇关于使用Try Catch时,并非所有代码路径都返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆