Error handling (Sending ex.Message to the client)

后端 未结 6 2015
野趣味
野趣味 2020-11-29 20:38

I have an ASP.NET Core 1.0 Web API application and trying to figure out how to pass the exception message to the client if a function that my controller is calling errors ou

6条回答
  •  渐次进展
    2020-11-29 20:57

    Rather than raising and catching an exception, how about you simplify your action to:

    // GET: api/customers/{id}
    [HttpGet("{id}", Name = "GetCustomer")]
    public IActionResult GetById(int id)
    {
        var customer = _customersService.GetCustomerById(id);
    
        if (customer == null)
        {
            return NotFound("Customer doesn't exist");        
        }
    
        return Ok(customer);
    }
    

    I wrote a blog post with some more options such as returning a JSON object instead of text.

提交回复
热议问题