Skip to content

Responses

As discussed previously, a Response is the result of a request or command. You should always check the IsSuccess property when you get back a Response. If this property is false, then the Error property will have details of the error.

Request Responses

For the response of a request, Response<T>, the Value property will be the T result, if the IsSuccess property is true.

Handling Errors

Greyhound provides compiler static analysis attributes to ensure that the result type (if applicable) and the Error property are not null based on the IsSuccess property of the Response. This is to ensure that you always check the IsSuccess property before accessing the Value or Error properties. If IsSuccess is false, then the Error property will be populated. When sending other requests or commands within a handler, it is normal to simply check the status of the Response and return the Error if it is not successful. For example:

public async Task<Response> Handle(AdjustEmployeeSalaryCommand command, CancellationToken cancellationToken)
{
// Get the employee
Response getEmployee = await mediator.Send(new GetEmployeeByIdRequest(command.EmployeeId), cancellationToken);
if (!getEmployee.IsSuccess) return getEmployee.Error; // Error handling
Employee employee = getEmployee.Value;
// Adjust the salary
employee.Salary = command.NewSalary;
employee = await employeeRepository.UpdateAsync(employee, cancellationToken);
// Return successful response
return Response.Success;
}

In certain limited cases, you can simply call ThrowIfUnsuccessful() on the Response to throw an exception if the response is not successful. This is normal in notification handlers that need to call commands. However, this method should not generally be used for handling errors.

More information on error handling and returning responses in handlers can be found in the Request and Command Handlers guide.