Документация Нэнси, кажется, говорит, что Pipelines.OnError
должен возвращать null
- в отличие от BeforeResponse
, который допускает как null
, так и Response
объект.
Все примеры как этот и много кода примеры здесь, в StackOverflow, показывают, что Response
возвращается в OnError, как и в BeforeRequest
.
Когда я пытаюсь вернуть строку HTTPStatus
для Pipelines.OnError, все работает нормально!
Но когда я пытаюсь вернуть ответ, я получаю ошибку компилятора: оператор «+=» не может применяться к операндам типа «Nancy.ErrorPipeline» и «лямбда-выражение».
Я почти точно эмулирую код в примере с Нэнси, за исключением того факта, что у меня это TinyIocContainer, а в примере используется контейнер StructureMap и загрузчик, производный от StructureMap.
Вот мой код:
const string errKey = "My proj error";
const string creationProblem = "Message creation (HTTP-POST)";
const string retrievalProblem = "Message retrieval (HTTP-GET)";
public void Initialize(IPipelines pipelines)
{
string jsonContentType = "application/json";
byte[] jsonFailedCreate = toJsonByteArray(creationProblem);
byte[] jsonFailedRetrieve = toJsonByteArray(retrievalProblem);
Response responseFailedCreate = new Response
{
StatusCode = HttpStatusCode.NotModified,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedCreate, 0, jsonFailedCreate.Length)
};
Response responseFailedRetrieve = new Response
{
StatusCode = HttpStatusCode.NotFound,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedRetrieve, 0, jsonFailedRetrieve.Length)
};
// POST - error in Create call
pipelines.OnError += (context, exception) =>
{
// POST - error during Create call
if (context.Request.Method == "POST")
return responsefailedCreate;
// GET - error during Retrieve call
else if (context.Request.Method == "GET")
return responseFailedRetrieve;
// All other cases - not supported
else
return HttpStatusCode.InternalServerError;
};
}
private byte[] toJsonByteArray(string plainString)
{
string jsonString = new JObject { { errKey, plainString } }.ToString();
byte[] result = Encoding.UTF8.GetBytes(jsonString);
return result;
}