user4342648
user4342648

Reputation:

Spring Framework Default Error Page to JSON

Sorry, if i am asking for lazy solution.

  @SpringBootConfiguration
  public class RestWebApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestWebApplication.class, args);
    }
  }

But when nothing is implemented, I expected

$ curl localhost:8080
{"timestamp":1384788106983,"error":"Not Found","status":404,"message":""}

But Got

<!DOCTYPE html><html><head><title>Apache Tomcat/8.5.9 - Error report</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style> </head><body><h1>HTTP Status 404 - /</h1><div class="line"></div><p><b>type</b> Status report</p><p><b>message</b> <u>/</u></p><p><b>description</b> <u>The requested resource is not available.</u></p><hr class="line"><h3>Apache Tomcat/8.5.9</h3></body></html>

Did i miss something ? So that i the error page is redirected as JSON Output?

Thanks in credit for your help.

Upvotes: 1

Views: 327

Answers (1)

Irakli
Irakli

Reputation: 983

You can try to use @ControllerAdvice that help for custom exception handling in spring.

This is the code I use :

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {


@ExceptionHandler()
public ResponseEntity<Exception> defaultErrorHandler(Exception e) throws Exception {
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}


@ExceptionHandler()
public ResponseEntity<ShemoException> defaultErrorHandler(ShemoException e) throws Exception {
    return new ResponseEntity<>(e,HttpStatus.NOT_FOUND);
}

This is custom Exception class:

import com.google.gson.JsonSyntaxException;



public class ShemoResponseMessage {

private int returnCode;
private String returnStatus;
private String errorSource;

// constructor
public ShemoResponseMessage() {
    returnCode = -1;
    returnStatus = null;
    errorSource = null;
}

// Constructor with individual response parts
public ShemoResponseMessage(int code, String status, String source) {
    returnCode = code;
    returnStatus = status;
    errorSource = source;

}



public ShemoResponseMessage(String shemoResponse) {
    this();

    if (shemoResponse == null) {
        return;
    }

    ShemoResponseMessage obj = null;

    try {

        obj = (ShemoResponseMessage) GsonUtils.createGson().fromJson(shemoResponse,
                ShemoResponseMessage.class);

    } catch (JsonSyntaxException e) {
        returnCode = -1;
        returnStatus = "";
        errorSource = "";
        return;
    }

    returnCode = obj.returnCode;
    returnStatus = obj.returnStatus;
    errorSource = obj.errorSource;

}


public ShemoResponseMessage(ShemoException e) {

    this(e.getMessage());

}

// Copy constructor
public ShemoResponseMessage(ShemoResponseMessage obj) {
    this(obj.getReturnCode(), obj.getReturnStatus(), obj.getErrorSource());

}

// getters
public int getReturnCode() {
    return returnCode;
}

public String getReturnStatus() {
    return returnStatus;
}

public String getErrorSource() {
    return errorSource;
}

// Get the json error message back. Creates a formatted message which can be used for throwing API exceptions
public String getShemoExeption() {
    String jsonResponse = GsonUtils.createGson().toJson(this, ShemoResponseMessage.class);
    return jsonResponse;

}

}

You can return any message you like

UPDATED

This is my custom exception class you can modify it per your need:

public class ShemoException extends Exception {

private static final long serialVersionUID = 1L;

Integer errorCode;
String errorMessage;

public ShemoException(Exception e) {
    super(e);
    errorCode = -1;
    errorMessage = "";
    String classNameMessage = getExceptionClassName(e);

    if (e.getMessage() != null)
        errorMessage = classNameMessage + ", " + e.getMessage();
    else
        errorMessage = classNameMessage;
}

private String getExceptionClassName(Exception e) {

    String className = new String();
    String classNameMessage = new String("");

    Class<? extends Exception> eClass = e.getClass();

    if (eClass != null) {

        className = eClass.getSimpleName();
        String words[] = className.split("(?=[A-Z])"); // Split Name by Upper Case for readability

        // put the Name back together, now with spaces between words
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            if (i > 0 && word.length() > 1)
                classNameMessage = classNameMessage.concat(" ");
            classNameMessage = classNameMessage.concat(word);
        }
    }

    return classNameMessage.trim();
}

public ShemoException(Integer errorCode, String errorMessage) {
    super();
    this.errorCode = errorCode;
    this.errorMessage = errorMessage;
}


public ShemoException(Integer errorCode, ShemoResponseMessage responseMessage) {
    super();
    this.errorCode = errorCode;
    this.errorMessage = responseMessage.getShemoExeption();
}

public Integer getErrorCode() {
    return errorCode;
}

public void setErrorCode(Integer errorCode) {
    this.errorCode = errorCode;
}

public String getErrorMessage() {
    return errorMessage;
}

public void setErrorMessage(String errorMessage) {
    this.errorMessage = errorMessage;
}

@Override
public String getMessage() {
    return getErrorMessage();

}

}

GsonUtils class:

import com.google.gson.Gson;

import com.google.gson.GsonBuilder; /** * Created by Shemo on 11/24/2015. */ public class GsonUtils {

public static String defaultDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ssZ";
private static GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat(defaultDateTimeFormat);

/***
 * Creates a GSON instance from the builder with the default date/time format
 *
 * @return the GSON instance
 */
public static Gson createGson() {
    // Create with default params
    gsonBuilder = gsonBuilder.setDateFormat(defaultDateTimeFormat);
    return gsonBuilder.create();
}

/***
 * Creates a GSON instance from the builder specifying custom date/time format
 *
 * @return the GSON instance
 */
public static Gson createGson(String dateTimeFormat) {
    // Create with the specified dateTimeFormat
    gsonBuilder = gsonBuilder.setDateFormat(dateTimeFormat);
    return gsonBuilder.create();
}

}

GSON library:

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>

Upvotes: 1

Related Questions