目录
1、具体示例
1.1自定义一个异常类,集成运行时异常
/**
* @Description 自定义异常
* @Date 2019-08-05 15:49
* @Created by 程序员
*/
@Data
public class BusinessException extends RuntimeException {
private String code;
public BusinessException(String message) {
super(message);
}
public BusinessException(String code, String message) {
super(message);
this.code = code;
}
}
1.2 处理自定义的异常
package com.lx.excepiton;
import com.lx.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.MessageFormat;
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
public GlobalExceptionHandler() {
}
@ExceptionHandler({BusinessException.class})
@ResponseBody
public ResultDTO businessExceptionHandler(BusinessException exception) {
String message = exception.getMessage();
StringBuilder sbException = new StringBuilder();
sbException.append(message);
sbException.append("\n");
for (StackTraceElement ele : exception.getStackTrace()) {
sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));
}
log.error(sbException.toString());
return ResultDTO.error(message);
}
@ExceptionHandler({Exception.class})
@ResponseBody
public ResultDTO exceptionHandler(Exception exception) {
String message = exception.getMessage();
StringBuilder sbException = new StringBuilder();
sbException.append(message);
sbException.append("\n");
for (StackTraceElement ele : exception.getStackTrace()) {
sbException.append(MessageFormat.format("\tat {0}.{1}({2}:{3})\n",
ele.getClassName(), ele.getMethodName(), ele.getFileName(), ele.getLineNumber()));
}
log.error(sbException.toString());
return ResultDTO.error(message);
}
}
1.3 创建controller测试
@GetMapping("/user/getById")
public String getUserById(@RequestParam String id){
log.info("id11111={}" , id);
// User byId = userService.getById(id);
// userService.queryFromCore();
// SaleContract saleContract = saleContractService.getById("1");
if(1 == 1){
// throw new BusinessException("自定义抛出的异常111");
throw new BusinessException("001","自定义抛出的异常222");
}
// return JSON.toJSONString(saleContract);
return "";
}