error: allow to specify where to get error location
Currently, the error location (file, line) is always retrieved from the current stack frame. The new argument `level` allows to change this. It has the same semantics as the `level` argument of the built-in Lua function `error`. Closes #9792 @TarantoolBot document Title: Document `level` argument of `box.error` and `box.error.new` Now, when used with a table argument, `box.error` and `box.error.new` also accept an optional second argument called `level`. It has the same meaning as the `level` argument of the built-in Lua function `error`: it specifies how to get the error location. With level 1 (the default), the error location is where `box.error` / `box.error.new` was called. Level 2 points the error to where the function that called `box.error` / `box.error.new` was called; and so on. Passing level 0 avoids addition of location information to the error. Example of using `level` with `box.error`: ```lua local json = require('json') local function inner(level) box.error({message = 'test'}, level) -- line:4 end local function outer(level) inner(level) -- line:8 end local ok, err ok, err = pcall(outer) print(json.encode(err.trace)) -- prints line:4 ok, err = pcall(outer, 1) print(json.encode(err.trace)) -- prints line:4 ok, err = pcall(outer, 2) print(json.encode(err.trace)) -- prints line:8 ok, err = pcall(outer, 0) print(json.encode(err.trace)) -- prints empty table ``` Example of using `level` with `box.error.new`: ```lua local json = require('json') local function inner(level) local err = box.error.new({message = 'test'}, level) -- line:4 return err end local function outer(level) local err = inner(level) -- line:9 return err end local err err = outer() print(json.encode(err.trace)) -- prints line:4 err = outer(1) print(json.encode(err.trace)) -- prints line:4 err = outer(2) print(json.encode(err.trace)) -- prints line:9 ok, err = pcall(outer, 0) print(json.encode(err.trace)) -- prints empty table ``` It is also possible to specify `level` when using `box.error` to re-raise an error created earlier with `box.error.new`, for example: ```lua local json = require('json') local err0 = box.error.new{message = 'test'} -- line:3 local function raise(err, level) box.error(err, level) -- line:6 end ok, err = pcall(raise, err0) print(json.encode(err.trace)) -- prints line:3 ok, err = pcall(raise, err0, 1) print(json.encode(err.trace)) -- prints line:6 ok, err = pcall(raise, err0, 0) print(json.encode(err.trace)) -- prints empty table ```
Showing
- changelogs/unreleased/gh-9792-error-level.md 4 additions, 0 deletionschangelogs/unreleased/gh-9792-error-level.md
- src/box/lua/error.cc 69 additions, 34 deletionssrc/box/lua/error.cc
- test/app-luatest/gh_9792_error_level_test.lua 186 additions, 0 deletionstest/app-luatest/gh_9792_error_level_test.lua
- test/box/error.result 2 additions, 2 deletionstest/box/error.result
Loading
Please register or sign in to comment