我有很多的控制器方法的WebAPI類似於以下:重構錯誤處理中的WebAPI控制器
public IHttpActionResult Delete(int id)
{
var command = new DeleteItemCommand() { Id = id };
try
{
_deleteCommandHandler.Handle(command);
}
catch (CommandHandlerResourceNotFoundException)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
catch(CommandHandlerException)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
// More catches etc...
return Ok();
}
命令處理程序(在此實例中_deleteCommandHandler
)早在執行注射的命令可以是內置在該方法中或使用WebApi的自動方法。
我想什麼做的是封裝的try/catch錯誤處理在一個私人的方法,並最終以類似控制器:
public IHttpActionResult Delete(int id)
{
var command = new DeleteItemCommand() { Id = id };
return ExecuteCommand(x => _deleteCommandHandler.Handle(command));
}
我不知道什麼是私人的簽名應該是ExecuteCommand
方法。