Browse Source

Add features to errorhandler

master
peter 4 years ago
parent
commit
98b271758b
5 changed files with 98 additions and 24 deletions
  1. 1
    1
      package.json
  2. 4
    4
      src/Backend.ts
  3. 1
    1
      src/Types.ts
  4. 5
    5
      src/Utils.ts
  5. 87
    13
      test/Test.ts

+ 1
- 1
package.json View File

@@ -1,6 +1,6 @@
1 1
 {
2 2
   "name": "rpclibrary",
3
-  "version": "1.6.0",
3
+  "version": "1.6.1",
4 4
   "description": "rpclibrary is a websocket on steroids!",
5 5
   "main": "./js/Index.js",
6 6
   "repository": {

+ 4
- 4
src/Backend.ts View File

@@ -40,8 +40,8 @@ export class RPCServer<
40 40
             this.sesame = U.makeSesameFunction(conf.sesame)
41 41
         }
42 42
 
43
-        this.errorHandler = (socket:I.Socket) => (error:any) => { 
44
-            if(conf.errorHandler) conf.errorHandler(socket, error)
43
+        this.errorHandler = (socket:I.Socket) => (error:any, rpcName:string, args: any[]) => { 
44
+            if(conf.errorHandler) conf.errorHandler(socket, error, rpcName, args)
45 45
             else throw error
46 46
         }
47 47
         
@@ -69,14 +69,14 @@ export class RPCServer<
69 69
         try{
70 70
             this.io.attach(this.ws)
71 71
             this.io.on('socket', (socket:I.Socket) => {
72
-                socket.on('error', (err) => this.errorHandler(socket, err))
72
+                socket.on('error', (err) => this.errorHandler(socket, err, "bind", []))
73 73
                 socket.on('close', () => this.closeHandler(socket))
74 74
                 this.connectionHandler(socket)
75 75
                 this.initRPCs(socket)
76 76
             })
77 77
             this.ws.listen(this.port, this.visibility)
78 78
         }catch(e){
79
-            this.errorHandler(this.io, e)
79
+            this.errorHandler(this.io, e, 'start', [])
80 80
         }
81 81
     }
82 82
 

+ 1
- 1
src/Types.ts View File

@@ -5,7 +5,7 @@ export type HookFunction<F extends AnyFunction = AnyFunction, SubresT = {}> = (.
5 5
 
6 6
 export type Visibility = "127.0.0.1" | "0.0.0.0"
7 7
 export type ConnectionHandler = (socket:I.Socket) => void
8
-export type ErrorHandler = (socket:I.Socket, error:any) => void
8
+export type ErrorHandler = (socket:I.Socket, error:any, rpcName: string, args: any[]) => void
9 9
 export type CloseHandler = (socket:I.Socket) =>  void
10 10
 export type SesameFunction = (sesame : string) => boolean
11 11
 export type ExceptionHandling = 'local' | 'remote'

+ 5
- 5
src/Utils.ts View File

@@ -74,7 +74,7 @@ export function rpcHooker<SubResT = {}>(socket: I.Socket, exporter:I.RPCExporter
74 74
         else
75 75
             rpcFunction = info.call
76 76
 
77
-        socket.hook(ret.uniqueName, callGenerator(socket, rpcFunction, errorHandler))
77
+        socket.hook(ret.uniqueName, callGenerator(info.name, socket, rpcFunction, errorHandler))
78 78
         return ret
79 79
     })
80 80
 }
@@ -83,7 +83,7 @@ export function rpcHooker<SubResT = {}>(socket: I.Socket, exporter:I.RPCExporter
83 83
  * Decorate an RPC with the error handler
84 84
  * @param rpcFunction the function to decorate
85 85
  */
86
-const callGenerator = (socket: I.Socket, rpcFunction : T.AnyFunction, errorHandler: T.ErrorHandler) : T.AnyFunction => {
86
+const callGenerator = (rpcName : string, socket: I.Socket, rpcFunction : T.AnyFunction, errorHandler: T.ErrorHandler) : T.AnyFunction => {
87 87
     const argsArr = extractArgs(rpcFunction)
88 88
     const args = argsArr.join(',')
89 89
     const argsStr = argsArr.map(stripAfterEquals).join(',')
@@ -92,7 +92,7 @@ const callGenerator = (socket: I.Socket, rpcFunction : T.AnyFunction, errorHandl
92 92
         try{
93 93
             return await rpcFunction(`+argsStr+`)
94 94
         }catch(e){
95
-            errorHandler(socket)(e)
95
+            errorHandler(socket)(e, rpcName, [`+args+`])
96 96
         }
97 97
     }`)
98 98
 }
@@ -126,7 +126,7 @@ const hookGenerator = (rpc:T.HookRPC<any, any, any>, errorHandler: T.ErrorHandle
126 126
                 })
127 127
                 return res
128 128
             }catch(e){
129
-                errorHandler(socket, e)
129
+                errorHandler(socket)(e, rpc.name, [`+args+`])
130 130
             }
131 131
         }`)
132 132
     }
@@ -139,7 +139,7 @@ const hookGenerator = (rpc:T.HookRPC<any, any, any>, errorHandler: T.ErrorHandle
139 139
             })
140 140
             return res
141 141
         }catch(e){
142
-            errorHandler(socket, e)
142
+            errorHandler(socket)(e, rpc.name, [`+args+`])
143 143
         }
144 144
     }`)
145 145
 }

+ 87
- 13
test/Test.ts View File

@@ -38,9 +38,9 @@ function makeServer(){
38 38
             function triggerCallback(...messages:any[]):number {return subcallback.apply({}, messages)},
39 39
         ]
40 40
     }],{
41
-        connectionHandler: (socket) => { console.log("connectionHandler OK") },
42
-        closeHandler: (socket) => { console.log("closeHandler OK") },
43
-        errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
41
+        connectionHandler: (socket) => {  },
42
+        closeHandler: (socket) => { },
43
+        errorHandler: (socket, err) => { throw err }
44 44
     })
45 45
 }
46 46
 
@@ -193,12 +193,12 @@ describe('It should do unhook', () => {
193 193
                 }
194 194
             }, 
195 195
             function checkCandy():string { cb(candy); return candy },
196
-            function stealCandy():string { candy = "_OK"; cb(candy); cb = (...any) => console.log.apply(console,["Server:", ...any]); return candy }
196
+            function stealCandy():string { candy = "_OK"; cb(candy); cb = () => {}; return candy }
197 197
         ]
198 198
         }],{
199
-            connectionHandler: (socket) => { console.log("connectionHandler OK") },
200
-            closeHandler: (socket) => { console.log("closeHandler OK") },
201
-            errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
199
+            connectionHandler: (socket) => { },
200
+            closeHandler: (socket) => { },
201
+            errorHandler: (socket, err) => { throw err }
202 202
         })
203 203
         client = new RPCSocket(21000, "localhost")
204 204
         return await client.connect()
@@ -210,14 +210,12 @@ describe('It should do unhook', () => {
210 210
     })
211 211
 
212 212
     it('Unhook+unsubscribe should stop callbacks', (done) => {
213
-        client['test'].subscribe(c => console.log("Client: "+c)).then( async (res: SubscriptionResponse) => {
213
+        client['test'].subscribe(c => {}).then( async (res: SubscriptionResponse) => {
214 214
             const r1 = await client['test'].checkCandy()
215 215
             const r3 = await client['test'].stealCandy()
216 216
             client.unhook(res.uuid)
217
-            console.log("---- No client output below this line")
218 217
             const r2 = await client['test'].checkCandy()
219 218
             const r4 = await client['test'].checkCandy()
220
-            console.log("---- More output below")
221 219
 
222 220
             if(r1 === "OK" && r3 === "_OK" && r2 === "_OK" && r4 === "_OK")
223 221
                 done()
@@ -382,15 +380,14 @@ describe('Error handling', ()=>{
382 380
         })
383 381
     })
384 382
 
385
-    it("RPC throws server with handler", (done)=>{
383
+    it("RPC throws on server with handler", (done)=>{
386 384
         let server = new RPCServer(21004, [ {
387 385
             name: 'createUser' as 'createUser',
388 386
             exportRPCs: () => [{
389 387
                 name: 'createUser' as 'createUser',
390 388
                 call: createUser
391 389
         }]}], {
392
-            errorHandler: (socket, e) => {
393
-                //console.log("EXPECTED SERVER EXCEPTION", String(e));
390
+            errorHandler: (socket, e, rpcName, args) => {
394 391
                 done()
395 392
             }
396 393
         })
@@ -416,3 +413,80 @@ describe('Error handling', ()=>{
416 413
         })
417 414
     })
418 415
 })
416
+
417
+describe("Errorhandler functionality", ()=>{
418
+    let createUser = async( user: {a:any,b:any}) => {
419
+        throw new Error("BAD BAD BAD")
420
+    }
421
+
422
+    it("correct values are passed to the handler", (done)=>{
423
+        let server = new RPCServer(21004, [ {
424
+            name: 'createUser' as 'createUser',
425
+            exportRPCs: () => [{
426
+                name: 'createUser' as 'createUser',
427
+                call: createUser
428
+        }]}], {
429
+            errorHandler: (socket, e, rpcName, args) => {
430
+                if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0]['a'] === 'a' && args[0]['b'] === 'b')
431
+                    done()
432
+            }
433
+        })
434
+
435
+        let sock = new RPCSocket(21004, 'localhost')
436
+        sock.connect().then((cli) => {
437
+            cli["createUser"]["createUser"]({
438
+                a:'a',
439
+                b:'b'
440
+            })
441
+            .then(r => {
442
+                if(r != null)
443
+                done("UNEXPECTED RESULT " + r)
444
+            })
445
+            .catch((e) => {
446
+                done("UNEXPECTED CLIENT ERROR " + e)
447
+                done(e)
448
+            })
449
+            .finally(() => {
450
+                sock.destroy()
451
+                server.destroy()
452
+            })
453
+        })
454
+    })
455
+
456
+    it("handler sees sesame", (done)=>{
457
+        let sesame = "AAAAAAAAAAAAAAA"
458
+        let server = new RPCServer(21004, [ {
459
+            name: 'createUser' as 'createUser',
460
+            exportRPCs: () => [{
461
+                name: 'createUser' as 'createUser',
462
+                call: createUser
463
+        }]}], {
464
+            sesame: sesame,
465
+            errorHandler: (socket, e, rpcName, args) => {
466
+                if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0] === sesame && args[1]['a'] === 'a' && args[1]['b'] === 'b')
467
+                    done()
468
+            }
469
+            
470
+        })
471
+
472
+        let sock = new RPCSocket(21004, 'localhost')
473
+        sock.connect(sesame).then((cli) => {
474
+            cli["createUser"]["createUser"]({
475
+                a:'a',
476
+                b:'b'
477
+            })
478
+            .then(r => {
479
+                if(r != null)
480
+                done("UNEXPECTED RESULT " + r)
481
+            })
482
+            .catch((e) => {
483
+                done("UNEXPECTED CLIENT ERROR " + e)
484
+                done(e)
485
+            })
486
+            .finally(() => {
487
+                sock.destroy()
488
+                server.destroy()
489
+            })
490
+        })
491
+    })
492
+})

Loading…
Cancel
Save