zm
2020-05-18 a18bfacbf56b401f6e0fdae8710fbca4df8cff77
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package cn.autoform.fw.exception;
 
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import cn.autoform.fw.utility.ConstMap;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
 
@Controller
public class TokenErrorController extends BasicErrorController {
 
    public TokenErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }
 
    @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);
        String exceptionStr = (String) body.get("exception");
        if (null != exceptionStr && !"".equals(exceptionStr)) {
            if (exceptionStr.equals(ExpiredJwtException.class.getName())) {
                body.put(ConstMap.STATUS, HttpStatus.FORBIDDEN.value());
                status = HttpStatus.FORBIDDEN;
                body.put(ConstMap.RSPCODE, "100003");
                body.put(ConstMap.RSPDESC, "token已过期");
            } else if (exceptionStr.equals(SignatureException.class.getName())) {
                body.put(ConstMap.STATUS, HttpStatus.FORBIDDEN.value());
                status = HttpStatus.FORBIDDEN;
                body.put(ConstMap.RSPCODE, "100003");
                body.put(ConstMap.RSPDESC, "token无效");
            } else if (exceptionStr.equals(RowOverLengthException.class.getName())) {
                body.put(ConstMap.STATUS, HttpStatus.OK.value());
                status = HttpStatus.OK;
                body.put(ConstMap.RSPCODE, "100004");
                body.put(ConstMap.RSPDESC, "表单字段过多,超过DB限制!");
            }
            body.remove("timestamp");
            body.remove("error");
            body.remove("exception");
            body.remove("message");
            body.remove("path");
        }
        return new ResponseEntity<>(body, status);
    }
 
    @Override
    public String getErrorPath() {
        return ConstMap.PATH;
    }
}