From ef4bb777f24395051cb452c945a27453de7965d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Preu=C3=9F?= Date: Mon, 4 Mar 2024 10:06:13 +0100 Subject: [PATCH] Handle errors in print requests --- README.md | 23 +++++++++++++++++++++-- index.js | 45 +++++++++++++++++++++++++++++---------------- 2 files changed, 50 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 6795537..a929ae0 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ curl --location 'http://127.0.0.1:1903/printers/PM-241-BT%20(Network)/print' \ --form 'copies="1"' ``` -#### Response: +#### Successful Response: > On windows the response does not return any real job id. Instead, it returns a 0. @@ -96,4 +96,23 @@ curl --location 'http://127.0.0.1:1903/printers/PM-241-BT%20(Network)/print' \ "1" ] } -``` \ No newline at end of file +``` + +#### Error Responses: + +If the request is not successful, the response will contain an error message and an error id. + +```json +{ + "error": "Missing PDF file", + "error_id": "missing_pdf" +} +``` + +Here is a list of possible error ids (but not all of them are implemented yet): + +| Error ID | Description | +|---------------|-------------------------------| +| missing_pdf | Missing PDF file | +| invalid_label | Invalid label format | +| null | Unsuccessful print job: {...} | \ No newline at end of file diff --git a/index.js b/index.js index 40fcfd9..015cccc 100644 --- a/index.js +++ b/index.js @@ -19,15 +19,21 @@ app.get('/', (req, res) => { }) app.get('/printers', async (req, res) => { - const printers = await getPrinters() - return res.json(printers.map(printer => { - return { - default: false, - format: 'PDF', - id: printer.printer || printer.deviceId, - name: printer.printer || printer.name, - } - })) + try { + const printers = await getPrinters() + + return res.json(printers.map(printer => { + return { + default: false, + format: 'PDF', + id: printer.printer || printer.deviceId, + name: printer.printer || printer.name, + } + })) + } catch (e) { + console.error('Error getting printers', e) + return res.json([]) + } }) app.post('/printers/:printer/print', upload.single('file'), async (req, res) => { @@ -36,14 +42,21 @@ app.post('/printers/:printer/print', upload.single('file'), async (req, res) => // query: user-id: string, docType: label // form data: file: binary, copies: string, shipment-ids: string - const fileToPrint = req.file.path - const printJob = await print(fileToPrint, printer) - const jobId = getRequestId(printJob) - - return res.json({ - jobs: [jobId], - }) + try { + const fileToPrint = req.file.path + const printJob = await print(fileToPrint, printer) + const jobId = getRequestId(printJob) + return res.json({ + jobs: [jobId], + }) + } catch (e) { + console.error('Error printing', e) + return res.status(400).json({ + error: 'Unsuccessful print job: ' + e.message, + error_id: null, + }) + } }) app.listen(port, () => {