Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

how to get error code from exception in c#

try {
	// some operation causing an exception
}
catch (SqlException e) {
	if (e.ErrorCode == 0x80131904)
      	// ...
		return null;
	throw;
}
Comment

c# return error status code based on exception

return new StatusCodeResult(HttpStatusCode.NotModified, this);
Comment

c# return error status code based on exception

return new ContentResult() { 
    StatusCode = 404, 
    Content = "Not found" 
};
Comment

c# return error status code based on exception

return new NotModified();

public class NotModified : IHttpActionResult
{
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.NotModified);
        return Task.FromResult(response);
    }
}
Comment

c# return error status code based on exception

[HttpGet]
    public ActionResult<YOUROBJECT> Get()
    {
        return StatusCode(304);
    }
Comment

c# return error status code based on exception

[HttpGet]
    public ActionResult<YOUROBJECT> Get()
    {
        return StatusCode(304, YOUROBJECT); 
    }
Comment

c# return error status code based on exception

public IHttpActionResult GetUser(int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
        return StatusCode(HttpStatusCode.NotModified);
    }
    return Ok(user);
}
Comment

c# return error status code based on exception

namespace MyApplication.WebAPI.Controllers
{
    public class BaseController : ApiController
    {
        public T SendResponse<T>(T response, HttpStatusCode statusCode = HttpStatusCode.OK)
        {
            if (statusCode != HttpStatusCode.OK)
            {
                // leave it up to microsoft to make this way more complicated than it needs to be
                // seriously i used to be able to just set the status and leave it at that but nooo... now 
                // i need to throw an exception 
                var badResponse =
                    new HttpResponseMessage(statusCode)
                    {
                        Content =  new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json")
                    };

                throw new HttpResponseException(badResponse);
            }
            return response;
        }
    }
}


//and then just inherit from the BaseController

[RoutePrefix("api/devicemanagement")]
public class DeviceManagementController : BaseController
{...


//and then using it

[HttpGet]
[Route("device/search/{property}/{value}")]
public SearchForDeviceResponse SearchForDevice(string property, string value)
{
    //todo: limit search property here?
    var response = new SearchForDeviceResponse();

    var results = _deviceManagementBusiness.SearchForDevices(property, value);

    response.Success = true;
    response.Data = results;

    var statusCode = results == null || !results.Any() ? HttpStatusCode.NoContent : HttpStatusCode.OK;

    return SendResponse(response, statusCode);
}
Comment

c# return error status code based on exception

public HttpResponseMessage GetComputingDevice(string id)
    {
        ComputingDevice computingDevice =
            _db.Devices.OfType<ComputingDevice>()
                .SingleOrDefault(c => c.AssetId == id);

        if (computingDevice == null)
        {
            return this.Request.CreateResponse(HttpStatusCode.NotFound);
        }

        if (this.Request.ClientHasStaleData(computingDevice.ModifiedDate))
        {
            return this.Request.CreateResponse<ComputingDevice>(
                HttpStatusCode.OK, computingDevice);
        }
        else
        {
            return this.Request.CreateResponse(HttpStatusCode.NotModified);
        }
    }
Comment

c# return error status code based on exception

[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
         return new HttpResponseMessage(HttpStatusCode.NotModified);
    }
    return request.CreateResponse(HttpStatusCode.OK, user);
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: osk c# 
Csharp :: c# get app FileVersion 
Csharp :: how to set an expiry date on a program 
Csharp :: Set property of control on form by name 
Csharp :: afaik 
Csharp :: unity random.insideunitcircle 
Csharp :: c# user name session 
Csharp :: button pervious for picturebox c# 
Csharp :: tulpep notification window example c# 
Csharp :: select vs where linq 
Csharp :: unity organize variables in inspector 
Csharp :: c# extract after what is 
Csharp :: creating weighted graph in c# 
Csharp :: how to reset checkbox visual studio c# 
Csharp :: webtest fullscreen extend window maximize 
Csharp :: c# fold list 
Csharp :: c# isalphanumeric 
Csharp :: .net core string compare ignore case and accents 
Csharp :: create file gz c# 
Csharp :: poems 
Csharp :: client = matrice[indexselectedclient] as String[]; 
Csharp :: hacker typer.com 
Csharp :: tuples in c# 
Csharp :: as c# 
Csharp :: Make a variable public without showing in the inspector 
Csharp :: publish web app to linux or ubuntu 
Csharp :: c# listview 
Csharp :: c# String Uppercase and Lowercase method 
Csharp :: c# use enum in class 
Csharp :: how to resize a panel unity 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =