thanhpk
thanhpk

Reputation: 4297

How to return grpc error in nodejs

I want to return grpc error code and description in server-side. I have tried this

function sayHello(call, callback) {
  callback({error: {code: 400, message: "invalid input"});
}

but I got this exception from client

{ Error: Unknown Error
    at /home/thanh/email/node_modules/grpc/src/node/src/client.js:434:17 code: 2, metadata: Metadata { _internal_repr: {} } }

If I don't want to include error field in message definition like this.

message Hello {
  string name = 1;
  string error = 2; // don't want this
}

Then what is the proper way to send grpc error back to client ?

Upvotes: 7

Views: 14863

Answers (3)

fsb2023
fsb2023

Reputation: 23

To clarify what @avi and @murgatroid99 have said what you want to do is structure you callback like so:

import * as grpc from '@grpc/grpc-js';

try{
  somethingThatThrowsAnError();
}catch(e){
  return callback(
    {
      message: e ,
      code: grpc.status.NOT_FOUND
    },
    null,
  )
}

grpc.status.NOT_FOUND is just a integer, 5, and when the client gets an error response from the server you can read it off the err prop returned e.g.

const client = new MyServiceConstructor(
  address,
  grpc.credentials.createInsecure()
);

client.myMethod(
  myRequest,
  metadata ?? new grpc.Metadata(),
  (error: string, response: T_RESPONSE_TYPE) => {
    if (error) {
      if(error.code === grpc.status.NOT_FOUND) {
        return handleNotFound(error, myRequest)
      }

      return unknownError(error, myRequest)
    }

    return response
  },
);

Upvotes: 0

Jack
Jack

Reputation: 68

As a supplement, GRPC only allowed 16 kinds of error. You can check all error code from its site: https://grpc.io/docs/guides/error/#error-status-codes.

And here I found an example code for NodeJs error handling: https://github.com/avinassh/grpc-errors/blob/master/node/server.js

Upvotes: 3

avi
avi

Reputation: 9636

Change it to:

return callback({
  code: 400,
  message: "invalid input",
  status: grpc.status.INTERNAL
})

Upvotes: 11

Related Questions