Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an error from a Controller in Loopback 4?

I have a controller method

// ... inside a controller class

@get('/error', {})
async error() {
  throw new Error("This is the error text");
}

The response I'm getting from this error front-end is:

{ "error": { "statusCode": 500, "message": "Internal Server Error" } }

What I would like the error to be is:

{ "error": { "statusCode": 500, "message": "This is the error text" } }

How do I return an error from a controller in Loopback 4?

like image 421
Seph Reed Avatar asked Mar 22 '19 22:03

Seph Reed


People also ask

How do I return API error?

The most basic way of returning an error message from a REST API is to use the @ResponseStatus annotation. We can add the error message in the annotation's reason field. Although we can only return a generic error message, we can specify exception-specific error messages.

What is a controller in LoopBack?

Controllers. In LoopBack 4, controllers handle the request-response lifecycle for your API. Each function on a controller can be addressed individually to handle an incoming request (like a POST request to /todos ), to perform business logic, and to return a response.

How do I make my controller LoopBack?

A controller can be created for a model at runtime using the defineCrudRestController helper function from the @loopback/rest-crud package. It accepts a Model class and a CrudRestControllerOptions object.

What is loopback4?

Overview. LoopBack is an award-winning, highly extensible, open-source Node. js and TypeScript framework based on Express. It enables you to quickly create APIs and microservices composed from backend systems such as databases and SOAP or REST services.


1 Answers

Hello from the LoopBack team 👋

In your controller or repository, you should throw the Error exactly as shown in your question.

Now when LoopBack catches an error, it invokes reject action to handle it. The built-in implementation of reject logs a message via console.error and returns an HTTP response with 4xx/5xx error code and response body describing the error.

By default, LoopBack hides the actual error messages in HTTP responses. This is a security measure preventing the server from leaking potentially sensitive data (paths to files that could not be opened, IP addresses of backend service that could not be reached).

Under the hood, we use strong-error-handler to convert Error objects to HTTP responses. This module offers two modes:

  • Production mode (the default): 5xx errors don't include any additional information, 4xx errors include partial information.
  • Debug mode (debug: true): all error details are included on the response, including a full stack trace.

The debug mode can be enabled by adding the following line to your Application constructor:

this.bind(RestBindings.ERROR_WRITER_OPTIONS).to({debug: true});

Learn more in our docs: Sequence >> Handling errors

Alternatively, you can implement your own error handler and bind it as the sequence action reject. See Customizing sequence actions in our docs.

export class MyRejectProvider implements Provider<Reject> {
  constructor(
    @inject(RestBindings.SequenceActions.LOG_ERROR)
    protected logError: LogError,
    @inject(RestBindings.ERROR_WRITER_OPTIONS, {optional: true})
    protected errorWriterOptions?: ErrorWriterOptions,
  ) {}

  value(): Reject {
    return (context, error) => this.action(context, error);
  }

  action({request, response}: HandlerContext, error: Error) {
    const err = <HttpError>error;

    const statusCode = err.statusCode || err.status || 500;
    const body = // convert err to plain data object

    res.statusCode = statusCode;
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.end(JSON.stringify(body), 'utf-8');

    this.logError(error, statusCode, request);
  }
}
like image 183
Miroslav Bajtoš Avatar answered Jan 03 '23 21:01

Miroslav Bajtoš