-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathWebApiExceptionTranslator.cs
More file actions
67 lines (60 loc) · 2.88 KB
/
WebApiExceptionTranslator.cs
File metadata and controls
67 lines (60 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
namespace WebApiService.Code
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using Newtonsoft.Json;
// Allows translating exceptions thrown by the business layer to HttpResponseExceptions.
// This allows returning useful error information to the client.
public static class WebApiErrorResponseBuilder
{
public static HttpResponseMessage CreateErrorResponseOrNull(Exception thrownException,
HttpRequestMessage request)
{
if (thrownException is JsonSerializationException)
{
// Return when the supplied model (command or query) can't be deserialized.
return request.CreateErrorResponse(HttpStatusCode.BadRequest, thrownException.Message);
}
// Here are some examples of how certain exceptions can be mapped to error responses.
if (thrownException is ValidationException)
{
// Return when the supplied model (command or query) isn't valid.
return request.CreateResponse<ValidationResult>(HttpStatusCode.BadRequest,
((ValidationException)thrownException).ValidationResult);
}
if (thrownException is OptimisticConcurrencyException)
{
// Return when there was a concurrency conflict in updating the model.
return request.CreateErrorResponse(HttpStatusCode.Conflict, thrownException);
}
if (thrownException is SecurityException)
{
// Return when the current user doesn't have the proper rights to execute the requested
// operation or to access the requested resource.
return request.CreateErrorResponse(HttpStatusCode.Unauthorized, thrownException);
}
if (thrownException is KeyNotFoundException)
{
// Return when the requested resource does not exist anymore. Catching a KeyNotFoundException
// is an example, but you probably shouldn't throw KeyNotFoundException in this case, since it
// could be thrown for other reasons (such as program errors) in which case this branch should
// of course not execute.
return request.CreateErrorResponse(HttpStatusCode.NotFound, thrownException);
}
// If the thrown exception can't be handled: return null.
return null;
}
public static string GetValueOrNull(this HttpRequestHeaders headers, string name)
{
IEnumerable<string> values;
return headers.TryGetValues(name, out values) ? values.FirstOrDefault() : null;
}
}
}