0

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.

1
  • Discourage to refactor code to make it better? Seems like a bad place to be. Commented Apr 1, 2016 at 8:42

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.