W
W
WhatIsHTML2018-01-31 21:57:17
JavaScript
WhatIsHTML, 2018-01-31 21:57:17

How to correctly send sql error to client?

Hello. At hand NodeJs, Express, PostgreSql, pg-promise The
question arose of how to correctly catch and send sql errors to the client.
If the SQL query failed, for example, because the key is already in use, then everything is OK, I get an error and can send it to the client. But something tells me that it is undesirable to send it in its original form and it is at least not user-friendly. How is it done well? Maybe there are some npm packages that parse the error SQL code and give a readable concise information? Or take it apart?
In my case there is a request

self.updateInfo = function (user) {
   return db.query("UPDATE users SET name=${name}, username=${username}, email=${email} WHERE (id=${id} AND activated = true) RETURNING *;", user);
    }

In the controller, the usual then / catch
userSQL.updateInfo(user).then(function (newUser) {
    response.json({
      message: "user updated",
      data: newUser
    });
  }).catch(function (error) {
    handler.error(response, 400, error);
  });

An example of the SQL error I'm getting
{"message":{"name":"error","length":305,"severity":"ОШИБКА","code":"23505","detail":"Ключ \"(username)=(test)\" уже существует.","schema":"public","table":"users","constraint":"users_username_key","file":"nbtinsert.c","line":"434","routine":"_bt_check_unique"}}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2018-01-31
@melkij

Why send a request error to the client at all?
The request error is the place in the log and only there. To the client - HTTP 500 and "sorry, I couldn't" written in any way you like.
If a different message (or action) is required for a particular error, catch that particular error code. The admissibility of the login is usually checked by a preliminary request; they have not yet been delivered to the on conflict update. Plus, you can grab an advisory lock to eliminate the race condition and roll everything into one storage to save on the scheduler and the network.

D
d-stream, 2018-02-01
@d-stream

The normal option is not to make selects, but to call stored procedures, which at the basic level check the logical (business) consistency of the data and display a user friendly slap in the form "this code is already in use", there are not enough funds in the account", "there are not enough rights to perform this operation" and all "unpredictable" wrapping in try catch - throw out as 500 or something like that "a system error occurred, inform the developers. Details: ...." (well, or write to log)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question