whycxzp
2021-05-11 1f4b34448a1cb470d170e9d9462aeec2d216cf55
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
package com.whyc.exception.first;
 
import com.whyc.dto.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
 
/**
 * 1.针对RestController层捕捉异常,结果统一返回
 * 2.异常日志,本地独立部署测试日志记录 TODO
 */
@Slf4j
@RestControllerAdvice(annotations = RestController.class)
public class CustomExceptionResultHandler<T> {
 
    @ExceptionHandler(DefinedException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response sendErrorResponse2Defined(Exception exception){
        return new Response().set(0,((DefinedException)exception).getMessage());
    }
 
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response sendErrorResponse2System(Exception exception){
        exception.printStackTrace();
        if(exception instanceof DefinedException) {
            return this.sendErrorResponse2Defined(exception);
        }
        CodeAndMsg.FAIL.setMessage(exception.toString());
        log.error("发生异常:{}",exception.toString());
        return new Response().setMsg(0,exception.toString());
    }
 
}