package cn.reghao.oss.store.exception;

import cn.reghao.jutil.jdk.converter.DateTimeConverter;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理 filter 中抛出的异常
 * 需要配置 server.error.path=/error
 *
 * @author reghao
 * @date 2020-06-19 13:34:19
 */
@RestController
public class FilterExceptionHandler extends BasicErrorController {
    public FilterExceptionHandler() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = getStatus(request);

        Map<String,Object> map = new HashMap<>();
        map.put("code",body.get("status"));
        map.put("msg",body.get("message"));
        map.put("timestamp", DateTimeConverter.format(System.currentTimeMillis()));
        map.put("data",body.get("data"));
        return ResponseEntity.status(status).body(map);
    }
}
