Home > Back-end >  How to throw a server error when fetching JS
How to throw a server error when fetching JS

Time:12-17

I'm new in JavaScript and i have a task to post an email input from form to a node server,everything works fine,but i should implement this functionality:
When an email is [email protected], the server responds with the 422 status code and payload which contains the information about the error. Use browser developer tools to examine the response for this scenario. Display the error message in the browser using window.alert().
I created a customException,it gives me the error in the console,but the server still responds with the 200 status code,but as i understand,it should give an error and the post should not work.How to do this task,i have no idea..?
Fetch functions:

import { validateEmail } from './email-validator.js'

export const sendSubscribe = (emailInput) => {
    const isValidEmail = validateEmail(emailInput)
    if (isValidEmail === true) {
        sendData(emailInput);
        // if (emailInput === '[email protected]'){
        //     throw new CustomException('422');
        // }
    }
}

const sendHttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? {
            'Content-Type': 'application/json'
        } : {}
    }).then(response => {
        if (response.status >= 400) {
            return response.json().then(errResData => {
                const error = new Error('Something went wrong!');
                error.data = errResData;
                throw error;
            });
        }
        return response.json();
    });
};

const sendData = (emailInput) => {
    sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
        email: emailInput
    }).then(responseData => {
        console.log(responseData);
    }).catch(err => {
        console.log(err, err.data);
    });
}

function CustomException(message) {
    const error = new Error(message);
    error.code = "422";
    window.alert('Forbidden email,please change it!')
    return error;
  }
  
  CustomException.prototype = Object.create(Error.prototype);

Validate function:

const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']

export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))

export { VALID_EMAIL_ENDINGS as validEnding }

Please help.Thanks in advance!

CodePudding user response:

Something like this should work:

Server code:

Simplify validate function.

export const isValid = (email) => {
  if (email === '[email protected]') {
    return false
  }

  return true
}

Then on your route, something like this, assuming expressjs behind.

app.post('/subscribe', (req, res, next) => {
  const email = req.body.email

  if (!isValid(email)) {
    return res.status(433).send('Email is forbidden')
  }

  return res.status(200).send('Success')
})

In your frontend you can just post to /subscribe with the email payload

const sendHttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? {
            'Content-Type': 'application/json'
        } : {}
    })
    .then(response => response.json())
};

And in your sendData you can catch the error, like you're doing

const sendData = (emailInput) => {
    sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
        email: emailInput
    }).then(responseData => {
        console.log(responseData);
    }).catch(err => {
        console.log(err); // Email is forbidden
        window.alert('Boo!')
    });
}

Sidenote: In most cases prototyping should be avoided in javascript.

  • Related