Call super in constructor and assign a field in Kotlin? - constructor

I would like to initialise status field inside constructor apart of calling super.
class MyException : RuntimeException {
init {
val status: Status
}
constructor(status: Status) : super()
constructor(status: Status, cause: Throwable) : super(cause)
}
How can I achievie that?

That worked for me:
class MyException : RuntimeException {
val status: Status
constructor(status: Status) : super() {
this.status = status
}
constructor(status: Status, cause: Throwable) : super(cause) {
this.status = status
}
}

Related

MappingException for Map type of data

While saving Map type data in couchBase I am getting an exception
Caused by: org.springframework.data.mapping.MappingException: Couldn't find PersistentEntity for type java.lang.Object!
I've taken a map in DataModel
#Data
public class test {
private Map<String,Object> testMap;
}
I found this and override couchBase configuration to do customMapping in case of Object Type like
protected <R> R read(final TypeInformation<R> type, final CouchbaseDocument source,
final Object parent) {
if (Object.class == typeMapper.readType(source, type).getType()) {
return (R) source.export();
} else {
return super.read(type, source, parent);
}
}
It worked for the request like
{
"dummyMap":{
"key1":"val1",
"key2":"val2"
}
}
But failed for
{
"dummyMap":{
"key1":"val1",
"key2":"val2",
"objects":[
{
"key1":"val1",
"key2":"val2"
}
]
}
}
with exception
Caused by: java.lang.IllegalArgumentException: Basic type must not be null!
I guess it is because of the array. Please let me know what I am doing wrong.
I am using spring-data-couchbase version 2.0.4.RELEASE.
hi please use below code, its because type is null and couchbase mapping convertor cant read document
its must be work.
#Override
#SuppressWarnings("unchecked")
protected <R> R read(final TypeInformation<R> type, final CouchbaseDocument source, final Object parent) {
if (type == null)
return (R) source.export();
if (Object.class == typeMapper.readType(source, type).getType()) {
return (R) source.export();
} else {
return super.read(type, source, parent);
}
}

How to access StackTrace property form my Custom Exceptions in dot net core

I'm trying to implement my own custom exceptions in dot net core.
This is what I have so far:
public class WSException: Exception
{
// some custom stuff...
private readonly string _developerMessage = "";
public string DeveloperMessage { get { return _developerMessage; } }
public WSException() {}
public WSException(string message) : base(message) {
this._developerMessage = message;
}
public WSException(string message, Exception inner) : base(message, inner) {
this._developerMessage = message;
}
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
public WSException(string message) : base(message) {
this._developerMessage = (String.IsNullOrWhiteSpace(developerMessage) ? message : developerMessage);
}
}
When I catch a general exception, I try to create one of my own (a WSException) to handle it in a common way, like this:
try {
// whatever
}
catch (WSException e) {
HandleException(e);
}
catch (Exception e) {
HandleException(new WSException(e));
}
When I do it like that, e.Source and e.StackTrace are null, and when I try to assign StackTrace I get a Propery or indexer 'Exception.StackTrace' cannot be assigned to --it is read only.
How should such I implement this constructor?
public WSException(Exception ex) : base(ex.Message, ex.InnerException) {
_developerMessage = ex.Message;
Source = ex.Source;
//StackTrace = ex.StackTrace; // cannot be assigned to, it's read only
}
The workaround I found so far is to handle it when I'm serializing the error to json, something like this:
public class WSExceptionJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ex = value as WSException;
writer.WriteStartObject();
// buch of properties[...]
string stackTrace = null;
if (ex.StackTrace != null) {
stackTrace = ex.StackTrace;
} else if (ex.InnerException != null && ex.InnerException.StackTrace != null) {
stackTrace = ex.InnerException.StackTrace;
} else {
stackTrace = null;
}
writer.WritePropertyName("stacktrace");
serializer.Serialize(writer, stackTrace.Split('\n'));
writer.WriteEndObject();
}
But it feels too hacky

Test with JUnit an request

I wanna to test an request with JUnit with an request like this but RxUtils.applySchedulersAndErrorMapper() return null. Is any possibilities to test that?
override fun onContinueClicked(phoneNumber: String) {
mView.showLoading()
mUserService.checkUserApprovedStatus(phoneNumber)
.compose(RxUtils.applySchedulersAndErrorMapper())
.subscribe({ response ->
//Success
}, { error ->
//Error
})
}
here is where I setup the presenter and mUserService for presenter
#Mock
private PhoneContract.View view;
#Mock
private UserService userService;
#Before
public void setup() {
presenter = new PhonePresenter(this.view);
presenter.mUserService = userService;
}
here is the test method
#Test
public void onContinueClicked_SendJustNumbers() {
String phoneNumber = "(01234567890)";
// when
presenter.onContinueClicked(phoneNumber);
// then
verify(view, times(1)).showLoading();
}
and here is the RXUtils class:
class RxUtils {
companion object {
#SuppressLint("CheckResult")
fun <E> applySchedulersAndErrorMapper(): ObservableTransformer<E, E> {
return ObservableTransformer { o ->
o.flatMap(Function<E, ObservableSource<E>> { element ->
val genericResponse = element as GenericResponse<*>
#Suppress("UNCHECKED_CAST")
return#Function Observable.just(genericResponse as E)
}).onErrorResumeNext(Function<Throwable, ObservableSource<E>> { t ->
if (t is ApiException) {
return#Function Observable.error(t)
}
var genericResponse: GenericResponse<*>? = null
return#Function Observable.error(ApiException(t.message ?: "", genericResponse?.result ?: Result()))
})
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
}
}
}
}
Here is the stacktrace where I receive null for RxUtils.applySchedulersAndErrorMapper()
java.lang.NullPointerException
If it relates to the SDK, it probably won't work in a unit test. You didn't include your imports, so it's impossible to tell at a glance, but I know from experience that you can't use this in a unit test
AndroidSchedulers.mainThread()
You need to replace that with, say, Schedulers.trampoline()
Example of how to set a custom scheduler for testing
Note, this is only an example, and there are other valid solutions.
class RxUtils {
companion object {
// add this
#VisibleForTesting var mainScheduler = AndroidSchedulers.mainThread()
#VisibleForTesting var ioScheduler = Schedulers.io()
#SuppressLint("CheckResult")
fun <E> applySchedulersAndErrorMapper(): ObservableTransformer<E, E> {
return ObservableTransformer { o ->
o.flatMap(Function<E, ObservableSource<E>> { element ->
val genericResponse = element as GenericResponse<*>
#Suppress("UNCHECKED_CAST")
return#Function Observable.just(genericResponse as E)
}).onErrorResumeNext(Function<Throwable, ObservableSource<E>> { t ->
if (t is ApiException) {
return#Function Observable.error(t)
}
var genericResponse: GenericResponse<*>? = null
return#Function Observable.error(ApiException(t.message ?: "", genericResponse?.result ?: Result()))
})
.observeOn(mainScheduler)
.subscribeOn(ioScheduler)
}
}
}
}
And in your test:
#Before fun setup() {
RxUtils.mainScheduler = Schedulers.trampoline()
RxUtils.ioScheduler = Schedulers.trampoline()
}
#After fun teardown() {
RxUtils.mainScheduler = AndroidSchedulers.mainThread()
RxUtils.ioScheduler = Schedulers.io()
}
EDIT in response to updated post with more information on test
First of all, you should post WAY MORE CODE. It's frustrating having to pull it out of you by dribs and drabs. Anyway. You have the following:
#Mock
private UserService userService;
That creates a mock UserService, sure, but it doesn't stub anything. When you call userService.anyFunctionAtAll(), it will return null by default. There's your NPE. You have to stub it. For example:
Mockito.when(userService.anyFunctionAtAll()).thenReturn(somePredeterminedValue)
Please refer to the Mockito website for more information.

Spring Rest Post Request Enumeration property

I am using Spring version 4.2 with Spring boot. I have a post request
http://localhost:3000/api/standards/
for which I have the following json request body
{
"standardName": "MyStandard",
"language": "Java",
}
All I want is to save a Standard entity. The 'language' property of the StandardEntity is of type Enum.
My Controller method looks like this
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Standard> createStandard(#Validated #RequestBody Standard standard ) {
standardService.createStandard(standard);
return new ResponseEntity<Standard>(standard, HttpStatus.CREATED);
}
But inside the controller the standard.getLangauge() is always null.
I have tried the #InitBinder and adding #JsonCreator to the Language enum but none of them works for me.
My Enum looks like this
public enum Language {
#JsonProperty("java")Java("java"),
#JsonProperty("sql")Sql("sql");
private String value;
private Language(String value) {
this.value = value;
}
public static Language fromValue(String value) {
for (Language language : values()) {
if (language.value.equalsIgnoreCase(value)) {
return language;
}
}
throw new IllegalArgumentException(
"Unknown enum type " + value + ", Allowed values are " + Arrays.toString(values()));
}
#Override
public String toString() {
return value;
}
#JsonCreator
public static Language create(String value) {
System.out.println("in json creator "+value);
if (value == null) {
throw new IllegalArgumentException();
}
for (Language v : values()) {
if (value.equals(v.getShortName())) {
return v;
}
}
throw new IllegalArgumentException();
}
Your request should be "java" instead of "Java"
{
"standardName": "MyStandard",
"language": "java"
}
When you are sending "Java" it in not able to map it to any Enum, so ideally it should throw an exception of type HttpMessageNotReadableException, check the stack trace there should be such exception.

How to get the exception ID and Title from Play!Framework?

I'm using Play!Framework with Java and I'd like to display in the console the exception ID and the title of the exception, and only that.
For testing, I created a Global object like this :
public class Global extends GlobalSettings {
#Override
public Result onError(RequestHeader request, Throwable throwable) {
Logger.info(Json.toJson(throwable).toString());
return super.onError(request, throwable);
}
}
This outputs a JSON formatted value of Throwable, wich contains this :
{
"cause": { ... },
"stackTrace": [ ... ],
"title": "Execution exception",
"description": "[NullPointerException: null]",
"id": "6epj67c35",
"message": "Execution exception[[NullPointerException: null]]",
"localizedMessage": "Execution exception[[NullPointerException: null]]",
"suppressed": []
}
Which proves that id and title are accessible, but if I try:
throwable.getId(); // does not exists
throwable.getTitle(); // Does not neither
So then, how can I access id and title ?
For that one, I looked at the Play20 code at Github, more precisely at those two classes :
UsefulException.java
PlayException.java
And in fact, Play throws a PlayException that extends UsefullException, containing the id, title and description. So here's how I did it :
public class Global extends GlobalSettings {
#Override
public Result onError(RequestHeader request, Throwable throwable) {
if (throwable instanceof PlayException) {
Logger.info(((PlayException) throwable).id);
}
return super.onError(request, throwable);
}
}
That's it ! :)