nodejs grpc server how to return error code
NodeJS GRPC Server: How to Return Error Code
When building a NodeJS GRPC server, it's important to handle errors gracefully. One way to do this is by returning error codes to the client. Here's how:
Using the GRPC Status Object
The easiest way to return error codes in a GRPC server is by using the built-in grpc.Status
object. This object provides a set of standard error codes that you can use to indicate different types of errors.
const grpc = require('grpc');
function sayHello(call, callback) {
if (!call.request.name) {
const error = new Error('Name is required');
error.code = grpc.status.INVALID_ARGUMENT;
return callback(error);
}
const message = `Hello, ${call.request.name}!`;
callback(null, { message });
}
In the example above, we're returning an error with the grpc.status.INVALID_ARGUMENT
code if the client did not provide a name in the request.
Custom Error Codes
Sometimes, you may need to create your own custom error codes. To do this, you can define a new error object and set its code
property to a custom value. Here's an example:
const grpc = require('grpc');
const CustomErrorCodes = {
MY_CUSTOM_ERROR: grpc.status.UNKNOWN + 1,
};
function sayHello(call, callback) {
if (!call.request.name) {
const error = new Error('Name is required');
error.code = CustomErrorCodes.MY_CUSTOM_ERROR;
return callback(error);
}
const message = `Hello, ${call.request.name}!`;
callback(null, { message });
}
In the example above, we've defined a new custom error code called MY_CUSTOM_ERROR
by adding one to the value of grpc.status.UNKNOWN
. We then use this custom error code when returning an error.
Returning Error Metadata
In addition to error codes, you may also need to return additional information about the error to the client. You can do this by setting metadata on the error object.
const grpc = require('grpc');
function sayHello(call, callback) {
const name = call.request.name;
if (!name) {
const error = new Error('Name is required');
error.code = grpc.status.INVALID_ARGUMENT;
error.metadata = new grpc.Metadata();
error.metadata.add('details', 'Name is a required field');
return callback(error);
}
const message = `Hello, ${name}!`;
callback(null, { message });
}
In the example above, we've added a new metadata key-value pair with the details of the error. This metadata can then be accessed by the client to determine more information about the error.