package com.house365.web.handler;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.controller.InterfaceController;

/**
 * 对外接口调用异常返回统一的响应
 * @author zhaodeshan
 * @version [版本号, 2015年5月6日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@ControllerAdvice(annotations = RestController.class,assignableTypes = {InterfaceController.class})
public class ExceptionHandlerController implements ResponseBodyAdvice<String>{
    @ExceptionHandler({Exception.class,RuntimeException.class})
    @ResponseBody
    public House365RestResponse<Object> handleAllException(Throwable ex) {
        ex.printStackTrace();
        House365RestResponse<Object> response = new House365RestResponse<Object>();
        response.setResult("0");
        response.setMsg(StringUtils.isBlank(ex.getMessage())?"接口调用失败":ex.getMessage());
        return response;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public String beforeBodyWrite(String body, MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
            ServerHttpResponse response) {
        // TODO Auto-generated method stub
        return body;
    }
}
