[Issue 17226] Exception during the generation of an assert message hides AssertError

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Feb 4 07:34:10 UTC 2023


https://issues.dlang.org/show_bug.cgi?id=17226

Salih Dincer <salihdb at hotmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |salihdb at hotmail.com

--- Comment #13 from Salih Dincer <salihdb at hotmail.com> ---
(In reply to Steven Schveighoffer from comment #12)
> What about creating a wrapper for format:
> 
> ```d
> string assertFormat(Args...)(string fmt, Args args)
> {
>    try {
>      return format(fmt, args);
>    } catch(Exception ex) {
>      return "Error while evaluating assert message: " ~ ex.toString;
>    }
> }
> 
> 
> // use like
> assert(i == 42, assertFormat("Something %s", functionThatThrows()));
> ```
> 
> This solves the problem, and also doesn't throw away any information. Plus
> it's not unpleasant to use.
> 
> Yes, it's opt in. So what? It can just be a best practice recommendation.

alias format = assertFormat; /*
import std.format;//*/

auto foo(T)(T P) {
  //assert(P == 43, format("T: %s", T.stringof));/*
  static assert(is(T == uint), format("T:", "int"));//*/
}

> onlineapp.d(6): Error: static assert:  "Error while evaluating assert message: FormatException@/dlang/dmd/linux/bin64/../../src/phobos/std/format/package.d(785): Orphan format arguments: args[0..1]"
> onlineapp.d(13):        instantiated from here: `foo!int`

I think the problem is also with static. Because above is static assert I got
at compile time.  But I got such 4 errors message with the following library
possibilities (without assertFormat):

> /dlang/dmd/linux/bin64/../../src/phobos/std/exception.d(518): Error: uncaught CTFE exception `std.format.FormatException("Orphan format arguments: args[0..1]")`
> onlineapp.d(6):        called from here: `format("T:", "int")`
> onlineapp.d(6): Error: static assert:  __error
> onlineapp.d(13):        instantiated from here: `foo!int`


//alias format = assertFormat; /*
import std.format;//*/

auto foo(T)(T P) {
  //assert(P == 43, format("T: %s", T.stringof));/*
  static assert(is(T == uint), format("T:", "int"));//*/
}

import std.stdio;
void main() {
  enum char D = 68;
  assertFormat("Hello %s and World", D).writeln;
  foo!int(42);
}
string assertFormat(Args...)(string fmt, Args args)
{
  import std.format : _format = format;
  try
  {
    return _format(fmt, args);
  }
  catch(Exception ex)
  {
    enum m = "Error while evaluating assert message: ";
    return m ~ ex.toString;
  }
}

SDB at 79

--


More information about the Digitalmars-d-bugs mailing list