|
3 | 3 | using System.Threading.Tasks;
|
4 | 4 | using JsonApiDotNetCore.Internal;
|
5 | 5 | using JsonApiDotNetCore.Serialization.Server;
|
| 6 | +using Microsoft.AspNetCore.Mvc; |
6 | 7 | using Microsoft.AspNetCore.Mvc.Formatters;
|
7 | 8 | using Microsoft.Extensions.Logging;
|
8 | 9 | using Newtonsoft.Json;
|
@@ -32,33 +33,39 @@ public async Task WriteAsync(OutputFormatterWriteContext context)
|
32 | 33 | throw new ArgumentNullException(nameof(context));
|
33 | 34 |
|
34 | 35 | var response = context.HttpContext.Response;
|
35 |
| - using (var writer = context.WriterFactory(response.Body, Encoding.UTF8)) |
| 36 | + using var writer = context.WriterFactory(response.Body, Encoding.UTF8); |
| 37 | + string responseContent; |
| 38 | + |
| 39 | + if (_serializer == null) |
| 40 | + { |
| 41 | + responseContent = JsonConvert.SerializeObject(context.Object); |
| 42 | + } |
| 43 | + else |
36 | 44 | {
|
37 | 45 | response.ContentType = Constants.ContentType;
|
38 |
| - string responseContent; |
39 |
| - if (_serializer == null) |
| 46 | + try |
40 | 47 | {
|
41 |
| - responseContent = JsonConvert.SerializeObject(context.Object); |
42 |
| - } |
43 |
| - else |
44 |
| - { |
45 |
| - try |
| 48 | + if (context.Object is ProblemDetails pd) |
46 | 49 | {
|
47 |
| - responseContent = _serializer.Serialize(context.Object); |
48 |
| - } |
49 |
| - catch (Exception e) |
50 |
| - { |
51 |
| - _logger?.LogError(new EventId(), e, "An error ocurred while formatting the response"); |
52 | 50 | var errors = new ErrorCollection();
|
53 |
| - errors.Add(new Error(400, e.Message, ErrorMeta.FromException(e))); |
| 51 | + errors.Add(new Error(pd.Status.Value, pd.Title, pd.Detail)); |
54 | 52 | responseContent = _serializer.Serialize(errors);
|
55 |
| - response.StatusCode = 400; |
| 53 | + } else |
| 54 | + { |
| 55 | + responseContent = _serializer.Serialize(context.Object); |
56 | 56 | }
|
57 | 57 | }
|
58 |
| - |
59 |
| - await writer.WriteAsync(responseContent); |
60 |
| - await writer.FlushAsync(); |
| 58 | + catch (Exception e) |
| 59 | + { |
| 60 | + _logger?.LogError(new EventId(), e, "An error ocurred while formatting the response"); |
| 61 | + var errors = new ErrorCollection(); |
| 62 | + errors.Add(new Error(500, e.Message, ErrorMeta.FromException(e))); |
| 63 | + responseContent = _serializer.Serialize(errors); |
| 64 | + response.StatusCode = 500; |
| 65 | + } |
61 | 66 | }
|
| 67 | + await writer.WriteAsync(responseContent); |
| 68 | + await writer.FlushAsync(); |
62 | 69 | }
|
63 | 70 | }
|
64 | 71 | }
|
0 commit comments