chen.lin
2 天以前 9140aee230de0ef41de9682a9353fbd372e2bcaa
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
package com.vincent.rsf.openApi.config;
 
import com.vincent.rsf.framework.exception.CoolException;
import com.vincent.rsf.openApi.entity.dto.CommonResponse;
import com.vincent.rsf.openApi.entity.dto.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
/**
 * 全局异常处理,返回值符合 8.2.3:code、msg、data(含 result:SUCCESS/FAIL)。
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
 
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
 
    @ExceptionHandler(CoolException.class)
    public ResponseEntity<CommonResponse> handleCoolException(CoolException e) {
        log.warn("业务异常: {}", e.getMessage());
        CommonResponse r = CommonResponse.error(e.getMessage());
        return ResponseEntity.status(HttpStatus.OK).body(r);
    }
 
    @ExceptionHandler(Exception.class)
    public ResponseEntity<CommonResponse> handleException(Exception e) {
        log.error("系统异常", e);
        String msg = e.getMessage() != null ? e.getMessage() : "系统异常";
        CommonResponse r = new CommonResponse();
        r.setCode(500);
        r.setMsg(msg);
        r.setData(ResultData.fail());
        return ResponseEntity.status(HttpStatus.OK).body(r);
    }
}