Giter Club home page Giter Club logo

Comments (3)

climba03003 avatar climba03003 commented on July 18, 2024

The current behavior is actually well documented.

Some things to consider in your custom error handler:
- you can `reply.send(data)`, which will behave as it would in [regular route
handlers](./Reply.md#senddata)
- objects are serialized, triggering the `preSerialization` lifecycle hook if
you have one defined
- strings, buffers, and streams are sent to the client, with appropriate
headers (no serialization)
- You can throw a new error in your custom error handler - errors (new error or
the received error parameter re-thrown) - will call the parent `errorHandler`.
- `onError` hook will be triggered once only for the first error being thrown.
- an error will not be triggered twice from a lifecycle hook - Fastify
internally monitors the error invocation to avoid infinite loops for errors
thrown in the reply phases of the lifecycle. (those after the route handler)

If you wish to skip preSerialization, you should send serialized content (e.g. string, Buffer, stream).

import Fastify from 'fastify';
const app = Fastify();

// 4. fallback to outer scoped and send
app.setErrorHandler(async (err, req, res) => {
  // You should send serialized content as last fallback.
  res.status(500).send(JSON.stringify({ msg: "error response" }));
  return res;
})

app.register((app, options, done)=>{
  // 1. enter route
  app.post('/', {handler: async (req, res) => {
    req.result = { msg: "hello"};
    res.status(200).send(req.result);
    return res;
  }})

  // 2. pre-serialize and throw
  app.addHook('preSerialization', async (req, res, payload) => {
    await asyncfunction();
    throw new Error('preSerialization error');
  });
  
  // 3. handle error and throw
  app.setErrorHandler(async (err, req, res) => {
    throw new Error('preSerialization error');
  });
  done();
});

const response = await app.inject({ method: 'POST', path: '/'})
console.log(response.body)

from fastify.

ritikrao1 avatar ritikrao1 commented on July 18, 2024

in my outer scoped error handler when i am sending error with this
res.header('content-type', 'application/json; charset=utf-8');
res.status(500).send(JSON.stringify({ msg: "error response" }));

this seems to be sending me json objects in response, with skipping preserialization hooks too

@climba03003 can you confirm if it will break in any case ?

from fastify.

climba03003 avatar climba03003 commented on July 18, 2024

can you confirm if it will break in any case ?

At least I don't see it will break in a case currently.
For my own project, I do send serialized content as last resort.
Working fine since I use fastify.

from fastify.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.