/java/

JEE + ExceptionMapper

2016-05-10 23:36:59

https://github.com/szalek/JEE-Thymeleaf-Layout

BusinessExceptionMapper

package pl.btbw.core;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class BusinessExceptionMapper implements ExceptionMapper

<businessexception> {

    @Override
    public Response toResponse(BusinessException ex) {

        return Response
                .status(ex.getCode())
                .header("Content-Type","application/json")
                .header("cause", ex.toString())
                .header("message", ex.getMessage())
                .entity(new ExceptionResponse(ex.getMessage(), ex.getCode()))
                .build();
    }

    class ExceptionResponse {
        public String message;
        public int code;

        public ExceptionResponse(String message, int code) {
            this.message = message;
            this.code = code;
        }
    }

}

BusinessException

package pl.btbw.core;

public class BusinessException extends RuntimeException {

    private int code = 500;

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String message, int code) {
        super(message);
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

and now, whenever we throw BusinessException from our business layer it will be translate to json response