Exception filters
Exception filters provide a means to transform exceptions thrown from microservice handlers into meaningful objects. For example, our rpcCreate
method currently throws an error with a string but what happens when the UserService throws an error or possibly the ORM. This method could throw a number of different errors and the only means that calling method knows what happened is to parse the error string. That’s simply unacceptable, so let’s fix it.
Start with creating a new exception class. Notice that our microservice exception extends RpcException and does not pass a HTTP status code in the constructor. These are the only differences between microservice exceptions and normal Nest.js API exceptions.
export
class
RpcValidationException
extends
RpcException
{
constructor
(
public
readonly
validationErrors
:ValidationError
[])
{
super
(
'Validation failed'
);
}
}
We can now change the rpcCreate
method to throw this exception when the...