简体   繁体   中英

Getting nullable object name via reflection from exception

We've lots of mapper classes and disencouraged to refactor (like checking with .HasValue ). In short mapping as following shortly:

public static MyDto MyEntityToMyDto(MyEntity entity)
    {
        MyDto dto = new MyDto ();
        try
        {
            dto.DtoAge = entity.Age.Value;
            dto.DtoBirthDate = entity.Birthdate.Value;
            dto.DtoNumber = entity.Number.Value;
        }
        catch (InvalidOperationException ex)
        {
            //Throw CustomException with message including the property name which is null like "Age field is null"
        }

        return dto;
    }

Seems exception Stacktrace knows which line it occured.

Does InvalidOperationException has any information about the field which it occured to get info via reflection? Can it be possible to obtain this information?

Or can it be achieved with ExceptionResource resource ? If so how?

Thanks in advance.

Unless the code that threw the exception annotated the exception with that kind of information, it is not available to you without great cost (think picking apart the debugging information to find the IL that corresponds to a stack trace line and then reassembling this to figure out the name of the field involved).

In this case the Nullable<T> throws the exception and it has no information whatsoever about the field it was stored in so it is impossible for it to get that kind of information.

In short, no, it cannot be achieved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM